Nitseg
Nitseg

Reputation: 1277

Dynamically rename twig variable

I have a section in a HTML doc that is repeated over and over. It is almost always the same excepted the form input variable name I need to access.

<div>
  {{ form_widget(form.name1.parameter)}}
</div>
<div>
  {{ form_widget(form.name2.parameter)}}
</div>
<div>
  {{ form_widget(form.name3.parameter)}}
</div>

I would like to make a unique template for these three and pass a parameter to this template so it changes the "nameX" parameter with proper value.

Meaning something like:

<div>
  {{ form_widget(form.{{goodname}}.parameter)}}
</div>

And in the calling twig template do something like:

{% include "divtemplate.html.twig" with {'goodname' : "name1"} %}
{% include "divtemplate.html.twig" with {'goodname' : "name2"} %}
{% include "divtemplate.html.twig" with {'goodname' : "name3"} %}

I'm able to use goodname alone in the document but not embeded in the form variable.

Do you know how to do this? I'm opened to workaround solutions.

Thanks a lot in advance


Edit: Correct way to do it (found thanks to Ahmed)

{% set subform = attribute(form, goodname) %} 
<div> 
     {{ form_widget(subform.parameter)}} 
</div>

Upvotes: 2

Views: 2170

Answers (2)

jsuggs
jsuggs

Reputation: 2652

You can also do something like this (similar to what I ended up doing) since I had more than 3 subforms that followed the same pattern.

{% for idx in range(1, 3) %}
    <div>
        {{ form_widget(attribute(form, 'name' ~ idx ~ '.parameter')) }} 
    </div>
{% endfor %}

Upvotes: 2

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

What about using the attribute twig helper which is commonly used to access a "dynamic" attribute of a variable.

Use {{ attribute(form, goodname) }} to access the form name1, name2 or name3 attributes. You can then call parameter on the returned object.

Upvotes: 2

Related Questions