开发者

Why Twig cannot use variable as index for array when I use set as capture?

In Twig, I can do a set in 2 ways

{% set car = 'Honda' %}

or

{% set car %}Honda{%endset%}

where the 2nd way is a 'capture'

When I try to use the varia开发者_JAVA百科ble as an index in an array for e.g.,

{{ cars[car].wheels | length }}

The 2nd way of setting a variable will not work. Why?


Turn on debug mode in Twig. Use the debug extension to view the variable in the 2 scenarios.

The first way

{% set car = 'Honda' %}
{% debug car %} 

will show you that car is still a string Honda

however, the 2nd way

{% set car %}Honda{%endset%}
{% debug car %}

will show you that car is now a

Twig_Markup Object ( [content:protected] => car )

So do not use capture as a way to set the variable if you want to use it as a key or index in an array.

Update: for Twig version greater than 1.5 use dump to replace debug

eg:

{% set car = 'Honda' %}
{% debug car %} 

eg:

{% set car %}Honda{%endset%}
{% debug car %}


You can also use 2nd way like this (you should trim car variable):

{% set car %}Honda{%endset%}

{{ cars[car|trim].wheels | length }}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜