johnohod johnohod - 5 months ago 38
Twig Question

Dynamic variable in Twig, example?

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 I would like to do someting like this:

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

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


You can build the field name with a variable then use it in the attribute function. As example:

{% set fieldName = "field" ~ %}

{{ attribute(gruppeType, fieldName) }}

A working example in this twigfiddle

Hope this help