Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 967
Kim Stacks Avatar asked Jul 05 '11 22:07

Kim Stacks


2 Answers

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 %}
like image 138
Kim Stacks Avatar answered Nov 11 '22 22:11

Kim Stacks


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

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

{{ cars[car|trim].wheels | length }}
like image 41
repincln Avatar answered Nov 11 '22 23:11

repincln