访问循环内的变量和 Twig 中的变量 [英] Access variable inside a loop and variable in Twig
问题描述
我想执行以下操作:
{% for i in 0..10 %}
{% if content_{{ i }}_raw == 2 %}
...
{% endif %}
{% endfor %}
是否可以在变量 content_1_raw
中获取 {{ i }}
并将 1
替换为 i 的值
?
Is it possible to get {{ i }}
inside the variable content_1_raw
and replace the 1
with the value of i
?
推荐答案
是的._context
变量保存当前上下文中的所有变量.您可以使用括号表示法或使用 属性访问其值
函数:
Yes. The _context
variable holds all variables in the current context. You can access its values with the bracket notation or using the attribute
function:
{% for i in 0..10 %}
{% if _context['content_' ~ i ~ '_raw'] == 2 %}
...
{% endif %}
{# or #}
{% if attribute(_context, 'content_' ~ i ~ '_raw') == 2 %}
...
{% endif %}
{% endfor %}
我在这里写了更多细节:Symfony2 - 如何访问树枝中的动态变量名
I have written more details about this here: Symfony2 - How to access dynamic variable names in twig
另外,不是写 'content_' ~ i ~ '_raw'
(波浪号,~
,是 字符串连接运算符),您也可以使用 字符串插值:
Also, instead of writing 'content_' ~ i ~ '_raw'
(tilde, ~
, is string concatenation operator), you can also use string interpolation:
"content_#{i}_raw"
这篇关于访问循环内的变量和 Twig 中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!