【发布时间】:2022-01-15 01:55:53
【问题描述】:
我在我的烧瓶项目中使用 jinja,并且我已经将一个元组传递给它。它运行良好,我正在使用引导表样式为每个国家/地区添加每一行。
<table class="table">
<thead>
<tr>
<th scope="col">Ranking</th>
<th scope="col">Country</th>
<th scope="col">Number of travellers</th>
<th scope="col">Travelling time</th>
<th scope="col">Rough Journey Cost</th>
</tr>
</thead>
<tbody>
{% for country in best_countries %}
<!-- sets the country name to the first part of the tuple-->
{% set countryName = country[0] %}
<!-- sets the country dictionary Which has the rough cost and value for travelling to that country -->
{% set countryDict = country[1] %}
{% set countryNumber = 0 %}
{% for roughCostText, roughCost in countryDict.items() %}
<tr>
<th scope="row">{{ loop.index }}</th>
<td>{{ countryName }}</td>
<td>num travellers here</td>
<td>num travelling time here</td>
<td>{{ roughCostText }}: <span class="cost-number">£{{ roughCost}}</span></td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
我的主要目标是在国家/地区排名数字上加一个并将其设置为第一列,但似乎每个国家/地区都将其保持为 1。 How to increment a variable on a for loop in jinja template? 我看了这篇文章并尝试了 loop.index 但它没有做任何事情
('Austria', {'Your journey will cost roughly': 4380.0})
以防万一,这就是每个列表项的外观,粗略的成本和国家/地区名称都可以正常工作。
任何帮助将不胜感激,我很困惑
【问题讨论】:
-
试试
{{ loop.parent.index }} -
jinja2.exceptions.UndefinedError: 'jinja2.runtime.LoopContext object' 没有属性'parent'
-
用
{{ forloop.index }}替换{{ loop.index }} -
return getattr(obj, attribute) jinja2.exceptions.UndefinedError: 'forloop' is undefined
-
{{ forloop.index }} {{ countryName }}