我在 Google App Engine 上有一个使用 Jinja2 的网站,所以版本是 2.6。在某些时候,我循环遍历列表以生成单选按钮,我希望默认选中第一个。 我的代码如下:
{% for publisher in publishers %}
<tr onclick="doNav('/spt/publisher/{{ publisher.id }}');" style="cursor: pointer;">
<td>{{ publisher.name }}</td>
<td>{{ publisher.songs }}</td>
<td><input form="export_publisher_form" onclick="event.cancelBubble = true;"
type="radio" name="export_publisher" value="{{ publisher.id }}"{% if loop.first %} checked{% endif %}></td>
</tr>
{% endfor %}
问题是,Jinja 似乎没有为 loop.first 返回任何值,也没有返回任何循环变量(我尝试使用 loop.index、loop.length 和 loop.cycle)。我做错了什么吗?
编辑: publishers 是一个看起来像这样的列表(为清楚起见缩进):
[{'id': 4974053165105152L, 'name': u'BMG', 'songs': 1},
{'id': 5888297083600896L, 'name': u'Emi', 'songs': 2},
{'id': 6099953071947776L, 'name': u'Ninja Tune', 'songs': 1},
{'id': 4762397176758272L, 'name': u'Sony', 'songs': 0},
{'id': 5325347130179584L, 'name': u'Universal', 'songs': 0},
{'id': 4815173734891520L, 'name': u'Warner', 'songs': 0}]
最佳答案
奇怪...您使用的是什么版本的 python?当我执行这段代码时,我得到以下输出:
{% for publisher in heater %}
<tr onclick="doNav('/spt/publisher/{{ publisher.id }}');" style="cursor: pointer;">
<td>{{ publisher.name }}</td>
<td>{{ publisher.songs }}</td>
<td><input form="export_publisher_form" onclick="event.cancelBubble = true;"
type="radio" name="export_publisher" value="{{ publisher.id }}"{% if loop.index == 2 %} checked{% endif %}></td>
</tr>
{% endfor %}
我检查了 Emi 2。你在看什么?
我也把你的数据改成了这样:
data = [{'id': 4974053165105152, 'name': 'BMG', 'songs': 1},
{'id': 5888297083600896, 'name': 'Emi', 'songs': 2},
{'id': 6099953071947776, 'name': 'Ninja Tune', 'songs': 1},
{'id': 4762397176758272, 'name': 'Sony', 'songs': 0},
{'id': 5325347130179584, 'name': 'Universal', 'songs': 0},
{'id': 4815173734891520, 'name': 'Warner', 'songs': 0}]
关于google-app-engine - Jinja2 不返回循环变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18448841/