回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我正在使用jinja2,我正在硬时间将idx变量设置为forloop。似乎Jinja在说idx是数据记录中的一个键。是否有一种方法可以设置idx将被视为循环中的一个变化变量,而不是一个键。谢谢</p>
<p>更新</p>
<p>我只需要循环索引1-6,因为数据中的索引0在其他地方使用</p>
<p><strong>如何在Python中将此代码转换为Jinja2</strong></p>
<pre><code>for idx in range(1,7):
print(report_rec.soundings.0.fuel_tank.idx.tank_no)
print(report_rec.soundings.0.fuel_tank.idx.length)
print(report_rec.soundings.0.fuel_tank.idx.volume)
</code></pre>
<p><strong>数据示例</strong></p>
<pre><code>
'soundings': [{
'pkey': '5f17a3f7c511d0b094326274',
'fuel_tank': [{
'tank_no': '1',
'length': '1',
'volume': 1.0,
}, {
'tank_no': '2',
'length': '2',
'volume': 2.0,
}, {
'tank_no': '3',
'length': '3',
'volume': 3.0,
}, {
'tank_no': '4',
'length': '4',
'volume': 4.0,
}, {
'tank_no': '5',
'length': '5',
'volume': 5.0,
}, {
'tank_no': '6',
'length': '6',
'volume': 6.0,
}, {
'tank_no': '7',
'length': '7',
'volume': 7.0,
}]
</code></pre>
<p><strong>这是我的HTML代码</strong></p>
<pre><code>{% for idx in range(1,7) %}
<tr>
<td>Tank No</td>
<td><input name="ft_tank_{{idx}}" type="text" value="{{ report_rec.soundings.0.fuel_tank.idx.tank_no }}"></td>
<td>CM</td>
<td><input name="ft_length_{{idx}}" type="text" value="{{ report_rec.soundings.0.fuel_tank.idx.length }}"></td>
<td>Volume(ltr)</td>
<td><input name="ft_volume_{{idx}}" type="text"value="{{ report_rec.soundings.0.fuel_tank.idx.volume }}" ></td>
</tr>
{% endfor %}
</code></pre>