Kim*_*cks 5 php arrays variables set twig
在Twig中,我可以通过两种方式进行设置
{% set car = 'Honda' %}
Run Code Online (Sandbox Code Playgroud)
要么
{% set car %}Honda{%endset%}
Run Code Online (Sandbox Code Playgroud)
第二种方式是'捕获'
当我尝试将变量用作数组中的索引时,例如,
{{ cars[car].wheels | length }}
Run Code Online (Sandbox Code Playgroud)
第二种设置变量的方法不起作用.为什么?
在Twig中打开调试模式.使用调试扩展来查看2个方案中的变量.
第一种方式
{% set car = 'Honda' %}
{% debug car %}
Run Code Online (Sandbox Code Playgroud)
会告诉你那辆车仍然是本田的一根绳子
然而,第二种方式
{% set car %}Honda{%endset%}
{% debug car %}
Run Code Online (Sandbox Code Playgroud)
会告诉你汽车现在是
Twig_Markup对象([content:protected] => car)
因此,如果要将变量用作数组中的键或索引,请不要使用捕获作为设置变量的方法.
更新:对于大于1.5的Twig版本,使用dump来替换debug
例如:
{% set car = 'Honda' %}
{% debug car %}
Run Code Online (Sandbox Code Playgroud)
例如:
{% set car %}Honda{%endset%}
{% debug car %}
Run Code Online (Sandbox Code Playgroud)