我需要在foreach循环中设置递增变量。并将增量变量值设置为我的文本字段的名称,但我有这个错误:
意外的“i”标记(期望定义的“for”标记的结束标记 靠近44号线)。 500内部服务器错误 - Twig_Error_Syntax
这是我的代码:
{% 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 %}
答案 0 :(得分:3)
Twig不知道速记增量运算符, 代码应该是
{% 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 %}
i
的初始化应该在for
- 循环之外,否则你每次都在循环中重置它
答案 1 :(得分:3)
您可以使用充当计数器的if let pop = town?.population {
if pop > 0
,这样您就不必为此手动处理临时变量:
loop.index
PS :如果您希望索引从0开始而不是1,请使用{% 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 %}
。