2017-04-03 47 views
3

我想製作自定義的樹枝標籤,類似於包含標籤,但從json文件中獲取變量。即在樹枝模板中,我寫{%section「header」%},它包含頭文件和從config.json文件附加變量到僅此模板。如何完成它?如何添加變量到自定義Twig的TokenParser?

我看了之前How to create a twig custom tag that executes a callback?幾次寫這個問題,但沒有發現任何具體的解決辦法如何解決我的問題

+0

的可能的複製[如何創建執行回調樹枝自定義標籤?(http://stackoverflow.com/questions/26170727/how-to- create-a-twig-custom-tag-that-executed-a-callback) – DarkBee

+0

不,這是不一樣的 – Julius

+0

它是一個很好的教程,讓你的節點開始。爲了傳遞參數給你的節點,我建議你查看[Block](https://searchcode.com/codesearch/view/46764421/)節點,'$ name = $ stream-> expect(Twig_Token :: NAME_TYPE) - > getValue();' – DarkBee

回答

1

好吧,我創建了一個小樣機,應該幫助你進一步的這條道路上,

MyNode.php

<?php 
    namespace Namespace\Base\Twig\Node; 

    class MyNode extends \Twig_Node { 
     private static $nodeCount = 1; 
     /** 
     * @param \Twig_Node_Expression $annotation 
     * @param \Twig_Node_Expression $keyInfo 
     * @param \Twig_NodeInterface $body 
     * @param integer    $lineno 
     * @param string    $tag 
     */ 
     public function __construct(\Twig_NodeInterface $body, $lineno, $tag = null) { 
      parent::__construct(['body' => $body,], array(), $lineno, $tag); 
     } 

     public function compile(\Twig_Compiler $compiler) { 
      $i = self::$nodeCount ++; 

      $json_data = json_decode(file_get_contents(__DIR__ . '/../../../../files/tmp/file.json'), true); 
      $compiler 
       ->addDebugInfo($this) 
       ->write('$context[\'injected_variable\'] = '.var_export($json_data, true).';') //add data to context 
       ->subcompile($this->getNode('body')) //compile everything in between the node 
       ->write('unset($context[\'injected_variable\']);'); //clean context afterwards 
     } 
    } 

file.json

{ 
    "glossary": { 
     "title": "example glossary", 
     "GlossDiv": { 
      "title": "S", 
      "GlossList": { 
       "GlossEntry": { 
        "ID": "SGML", 
        "SortAs": "SGML", 
        "GlossTerm": "Standard Generalized Markup Language", 
        "Acronym": "SGML", 
        "Abbrev": "ISO 8879:1986", 
        "GlossDef": { 
         "para": "A meta-markup language, used to create markup languages such as DocBook.", 
         "GlossSeeAlso": ["GML", "XML"] 
        }, 
        "GlossSee": "markup" 
       } 
      } 
     } 
    } 
} 

template.twig

<!DOCTYPE html> 
<html> 
    <head></head> 
    <body> 
     {% mynode%} 
      {{ injected_variable.glossary.title }} {# prints example glossary #} 
     {% endmynode %} 
    </body> 
</html> 
+0

非常感謝! – Julius

相關問題