Given:

$column = array( 'value_1' => 'on', 'value_2' => 'on', 'value_3' => 'off' ); $values= array('value_1', 'value_2', 'value_3'); 

Non-working example:

 {% for value in values %} <input type="checkbox" {% if column.{{value}} == 'on' %}checked{% endif %}> {% endfor %} 

The question is how to substitute the {{value}} variable into the condition? Maybe something like column.{value} , column.[value] , column.'value' ? But all this does not work. How to implement?

  • {{ column[value] }} tried? - Dmitriy Simushev

2 answers 2

why do you access the array element through the column.{{value}} ?

Try this option ...

 {% for value in values %} <input type="checkbox" {% if column[value] == 'on' %}checked{% endif %}> {% endfor %} 

Also try this option

 {% for value in values %} <input type="checkbox" {{ column[value] == 'on' ? 'checked' : '' }}> {% endfor %} 
  • It is suitable. Thank. - Pavel Sokolov
  • and what is the fundamental difference in the point and brackets, because in traditional cases this works (at least with arrays) - Pavel Sokolov
  • The fact that brackets work for your case, but the point - no. - Ipatiev
  • I mean in terms of Twig stuffing. Just curious. - Pavel Sokolov

Everything is much easier. To access the array key, you can use the syntax with square brackets:

 {% for value in values %} <input type="checkbox" {% if column[value] == 'on' %}checked{% endif %}> {% endfor %} 

Here is the TWIGFiddle worker with an example.