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 variable 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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With