如何将变量添加到自定义Twig的TokenParser?

时间:2017-04-03 13:31:55

标签: twig

我想制作自定义twig标签,类似于include标签,但是从json文件中获取变量。即在树枝模板中,我写了{%section" header" %},它包括头文件,并将config.json文件中的变量附加到此模板。怎么做到了?

我在写这个问题之前几次阅读How to create a twig custom tag that executes a callback?,但没有找到解决问题的具体方法

1 个答案:

答案 0 :(得分: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>