How to access dynamic variable names in twig?

php, symfony, twig

Solution

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.

Problem

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 }} ```

Original source