Why can't Twig use a variable as an index for an array when I use set as capture?

In Twig, I can make a dial in two ways

{% set car = 'Honda' %}

or

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

where the second way is "capture"

When I try to use a variable as an index in an array for example,

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

The second way to set the variable will not work. Why?

+5
source share
2 answers

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

First way

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

will show you that the car is still a Honda string

however the second way

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

will show you that the car is now

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

, .

: Twig 1,5 debug

:

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

:

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

, ( ):

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

{{ cars[car|trim].wheels | length }}
+2