Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic twig variable names

Tags:

twig

symfony

Given an array of variables sent to a twig template, such as:

$form   = $this->createForm( new ServiceItemType()
                           , $entity
                           , array( 'attr'=>
                                     array(
                                          'em'    => $this->EM()
                                         ,'group' => true
                           ) ) );

I want to capture the variables for easy access in twig. However:

{% for key, value in form.vars.attr %}
    {% set key = value %}
{% endfor %}

remaps the key variable in the for loop.

twig objects to:

{% for key, value in form.vars.attr %}
    {% set {{key}} = value %}
{% endfor %}

And stack as I am aware never seems to address set. Would anyone who knows, please indicate how to accomplish this variable assignment?

like image 473
Lighthart Avatar asked May 21 '26 03:05

Lighthart


1 Answers

I know this syntax works

{% render "..." with {(key): value} %}

Did you try the following syntax? As of March, Friday 22nd this syntax didn't work so you need to use a work around.

{% set (key) = value %}

An alternative to that would be to include a template and pass and form.vars.attr.

{% include "YourAwesomeBundle:Controller:template.html.twig" with form.vars.attr %}

You can also merge form.vars.attr with another array using the merge function.

{% set vars = {} %}
{% set vars = vars|merge(form.vars.attr) %}
{% include "YourAwesomeBundle:Controller:template.html.twig" with vars %}

Within the included template you will be able to use the variable em and group.

like image 189
Thomas Potaire Avatar answered May 22 '26 19:05

Thomas Potaire