Twig - Dynamic array key

Currently working on a tool built on Symfony. I am iterating over an array of configuration settings. The thing I want to achieve seemed simple enough:

I am trying to obtain a certain value. One of the keys has to be dynamic though. Below is a working example without the key being dynamic.

{% set id = tmod_config.content_1.id %}

("content_1" being the key in question)

The number at the end of the key has to be dynamic. I have tried a couple of things but wasn't able to achieve this. Up to this point I have access to the dynamic value, it just needs to be turned into a functioning key.

Any suggestions?

Question solved! Check the answers

Answer #1:

As it is an array you could use either..

{% set id = tmod_config[content_1].id %}

or

{% set id = attribute(tmod_config, content_1).id %}
Answered By: spacellama

Answer #2:

Solved the problem soon after posting it!

It can easily be done like this:

{% set id = tmod_config["content_" ~ contentId].id %}
Answered By: qooplmao
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles