PHP 具有内省功能的模板引擎

PHP template engine with introspection

我想根据模板的变量定义用于输入的表单字段。

因此我发现模板引擎需要内省之类的东西,这样我才能检索模板的变量。

Smarty 只提供了一个分配变量的列表,据我所知,Twig 只是处于调试模式。 你知道除了自己写引擎之外我还能怎么解决这个问题吗?

提前致谢

编辑以澄清:如果有类似 {{ foo }} 的内容,我想从模板中获取带有变量名称的字符串。这可能吗?

twig 中你有特殊变量 _context。这是一个变量,它将所有已知变量保存在模板中。您可以通过循环变量来检查它包含哪些变量,例如

{% for key in _context|keys %}
    {{ key }}<br />
{% endfor %}

您也可以使用此变量访问动态变量,例如

{% set my_fixed_var_bar = 'foobar' %}
{% set foo = 'bar' %}

{{ _context['my_fixed_var_'~bar]| default('N/A') }} {# with array notation #}
{{ attribute(_context, 'my_fixed_var_'~foo) | default('N/A') }} {# with attribute function #}

宏是一个例外,因为它们在 twig 中有自己的(可变)范围。这意味着它们不共享全局 _context 变量,而是拥有自己的变量。如果你想从宏外部访问变量,你只需要将 _context 传递给宏,例如

{% import _self as 'macros' %}

{% macro foo(context) %}
   {{ _context | keys | length }} {# 0 #}
   {{ context.my_fixed_var_bar }} {# foobar #}
{% endmacro %}

{{ macros.foo() }} {# 0 foobar #}

如果您需要访问 function/filter/extension class 中的变量 _context 您可以通过将选项 needs_context 设置为 true

$twig->addFunction(new \Twig\TwigFunction('my_function', function($context) {
     //do stuff
}, [ 'needs_context' => true, ]));

demo