gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:30:15 25 4
gpt4 key购买 nike

我想制作自定义 Twig 标签,类似于包含标签,但从 json 文件中获取变量。 IE。在 twig 模板中,我写了 {% section "header"%},它包含头文件并将 config.json 文件中的变量附加到此模板。如何实现?

我读了How to create a twig custom tag that executes a callback?之前写过几次这个问题,但没有找到任何具体的解决方案如何解决我的问题

最佳答案

好的,我已经创建了一个小模型,可以帮助您在这条道路上走得更远,

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
}
}

文件.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>

关于twig - 如何将变量添加到自定义 Twig 的 TokenParser?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43186032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com