Symfony2 - How to access dynamic variable names in a branch

I have variables in twig like

placeholder1 placeholder2 placeholderx 

To call them, I look at an array of "invoice" objects

 {% for invoices as invoice %} need to display here the placeholder followed by the invoice id number {{ placeholedr1 }} 

Any idea? Thanks.

+8
php symfony twig
source share
5 answers

I had the same problem - and, using this first answer, and after some additional research, I found that {{ attribute(_context, 'placeholder'~invoice.id) }} should work ( _context is a global context object containing all objects by name)

+19
source share

I think you could use the Twig attribute function.

http://twig.sensiolabs.org/doc/functions/attribute.html

+3
source share

My solution for this problem:

Create an array of placeholder (x). How:

 # Options $placeholders = array( 'placeholder1' => 'A', 'placeholder2' => 'B', 'placeholder3' => 'C', ); # Send to View ID invoice $id_placeholder = 2; 

Send both variables for viewing and in the template call:

 {{ placeholders["placeholder" ~ id_placeholder ] }} 

Fingerprint "B".

Hope this helps you.

+2
source share

Instead of using the attribute function , you can access the values โ€‹โ€‹of the _context array using the standard bracket too:

 {{ _context['placeholder' ~ id] }} 

I would personally use this because it is more concise and, in my opinion, more clear.

If strict_variables set to true , you should also use the default filter:

 {{ _context['placeholder' ~ id]|default }} {{ attribute(_context, 'placeholder' ~ id)|default }} 

Otherwise, you will get a Twig_Error_Runtime exception if the variable does not exist. For example, if you have the variables foo and bar , but try to output the baz variable (which does not exist), you will get this exception with the message Key "baz" for array with keys "foo, bar" does not exist .

A more detailed way to check for a variable is to use defined test :

 {% if _context['placeholder' ~ id] is defined %} ... {% endif %} 

With the default filter, you can also specify a default value, for example. null or string:

 {{ _context['placeholder' ~ id]|default(null) }} {{ attribute(_context, 'placeholder' ~ id)|default('Default value') }} 

If you omit the default value (that is, use |default instead of |default(somevalue) ), the default value is an empty string.

strict_variables is false by default, but I prefer to set it to true to avoid accidental problems caused by, for example, typos.

+2
source share

I found a solution:

 attribute(_context, 'placeholder'~invoice.id) 
0
source share

All Articles