Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig accessing array values using variables

Tags:

twig

{% set key = 'something' %}

My array has key something, I and can it access array['something'], but when I try to use variable in key like:

array[key]

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

like image 759
Wizard Avatar asked Oct 20 '25 21:10

Wizard


1 Answers

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

like image 195
Matteo Avatar answered Oct 25 '25 03:10

Matteo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!