好吧,我創建了一個小樣機,應該幫助你進一步的這條道路上,
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>
的可能的複製[如何創建執行回調樹枝自定義標籤?(http://stackoverflow.com/questions/26170727/how-to- create-a-twig-custom-tag-that-executed-a-callback) – DarkBee
不,這是不一樣的 – Julius
它是一個很好的教程,讓你的節點開始。爲了傳遞參數給你的節點,我建議你查看[Block](https://searchcode.com/codesearch/view/46764421/)節點,'$ name = $ stream-> expect(Twig_Token :: NAME_TYPE) - > getValue();' – DarkBee