Milos Cuculovic
Milos Cuculovic

Reputation: 20223

How to access dynamic variable names in twig?

I have some variables in twig like

placeholder1
placeholder2
placeholderx

To call them, I am looping through the array of objects "invoices"

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

Upvotes: 26

Views: 37183

Answers (5)

Einenlum
Einenlum

Reputation: 620

I guess you could use the Twig attribute function.

https://twig.symfony.com/doc/3.x/functions/attribute.html

Upvotes: 11

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

Instead of using the attribute function, you can also access values of the _context array with the regular bracket notation:

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

I would personally use this one as it's more concise and in my opinion clearer.

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

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

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

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

A more verbose way to check the existence of a variable is to use the defined test:

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

With the default filter you can also provide a default value, e.g. null or a string:

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

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

If you omit the default value (i.e. you use |default instead of |default(somevalue)), the default value will be an empty string.

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

Upvotes: 33

Bruno Rigolon
Bruno Rigolon

Reputation: 439

My solution for this problem:

Create array of placeholder(x). Like:

# Options
$placeholders = array(
    'placeholder1' => 'A',
    'placeholder2' => 'B',
    'placeholder3' => 'C',
);

# Send to View ID invoice
$id_placeholder = 2;

Send both variables for view and in your template call:

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

This print "B".

I hope this help you.

Upvotes: 4

Mathieu Jamot
Mathieu Jamot

Reputation: 311

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

Upvotes: 31

user1409904
user1409904

Reputation: 73

I found the solution:

attribute(_context, 'placeholder'~invoice.id)

Upvotes: 1

Related Questions