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.