2
votes

I need to set incremented variable in foreach loop. and set incremented variable value as name of my text field, but I've got this error:

Unexpected "i" tag (expecting closing tag for the "for" tag defined near line 44). 500 Internal Server Error - Twig_Error_Syntax

Here is my code:

{% for key, poll_option in poll_options %}
     {% set i = '' %}
        <input id="option_name" value="{{poll_option.option}}" name="se_pollbundle_polls[name_{{ i }}]" type="text">
     {% i++ %}
{% endfor %}
2

2 Answers

4
votes

You can use loop.index which acts as a counter so you don't have to manually handle a temp var for this:

{% for key, poll_option in poll_options %}
     <input id="option_name" value="{{ poll_option.option }}" name="se_pollbundle_polls[name_{{ loop.index }]" type="text">
{% endfor %}

PS: Use loop.index0 if you want the index to start at 0 instead of 1.

3
votes

Twig does not know about the shorthand increment operator, the code should be

{% set i = 0 %}
{% for key, poll_option in poll_options %}
     <input id="option_name" value="{{poll_option.option}}" name="se_pollbundle_polls[name_{{ i }}]" type="text">
     {% set i = i + 1 %}
{% endfor %}

the initialisation of i should be outside the for-loop, otherwise you're resetting it each time in the loop