Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variable in Twig, example?

Tags:

twig

I don't quite understand how the attribute function in Twig works. Can somebody help me with an example?

I have a field in a SQL that is named dynamic. I could be eg "field27", but I don't know the number, the number is saved in radio.id. I would like to do someting like this:

{% for radio in gruppeType.radios %}
<td><!-- value of "field" + radio.id--></td>
{% endfor %}

How can I use field + radio.id as the name of the twig-variable?

like image 246
johnohod Avatar asked Oct 21 '16 12:10

johnohod


1 Answers

You can build the field name with a variable, then use it in the attribute function to access the data within the object/array. As example:

{% set fieldName = "field" ~ radio.id %}

{{ attribute(gruppeType, fieldName) }}

A working example can be seen in this twigfiddle

Hope this helps.

like image 53
Matteo Avatar answered Oct 16 '22 03:10

Matteo