Wizard Wizard - 10 months ago 143
Twig Question

Twig accessing array values using variables

{% set key = 'something' %}

has key something, I and can it access
, but when I try to use variable in key like:


I'm getting error that array key not exist. So question is how to access array keys using variables.

Answer Source

You can use the attribute function:

{{ attribute(array, key) }}

From the doc:

addition, the defined test can check for the existence of a dynamic attribute:

{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}

Hope this help