在使用jinja(Flask)的2个分离柱中使用2作为回路数据?

2024-09-28 18:54:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个从视图生成的列表。我想用html将其呈现为我运行了两个for循环的表

{% for row in country %}
   <tr>
   <td>{{ row }}</td>
{% endfor %}
{% for count in death %}
   <tr>
   <td>{{ count }}</td>
{% endfor %}

乡村死亡 ★ 美国16691★ 西班牙15447★ 意大利18279

但我需要像

★ 美国16691
★ 西班牙15447
★ 意大利18279


Tags: in视图列表forhtmlcountcountrytr
3条回答

对于3嵌套循环,以下是代码

{% for row in country %}
  {% set outer_loop = loop %}
  {% for confirm in confirmed %}
     {% set inner_loop = loop %}
     {% for dead in death %}
        {% if outer_loop.index0 == loop.index0 %}  {% if inner_loop.index0 == 
        loop.index0 %}
      <tr><td>{{ row }}</td> <td> {{ confirm }}</td> <td> {{ dead }} </td></tr>
     {% endif %}
     {% endfor %}
  {% endfor %}

{%endfor%}

如果您将列表合并到视图中,您的模板可能会更好

他认为:

statistics = zip(country, death)

在模板中,您现在可以遍历元组列表,如下所示:

[('United States', '16,691'), ('Spain', '15,447'), ('Italy', '18,279')]

我不确定这在jinja中是如何工作的,但它消除了嵌套for循环的需要

可以通过比较两个循环的索引(计数器)值来实现这一点。只有当它们相等时,才会在新行上渲染它们

The special loop variable always points to the innermost loop. If it’s desired to have access to an outer loop it’s possible to alias it:

{% for row in country %}
     {% set outer_loop = loop %}
     {% for count in death %}
         {% if outer_loop.index0 == loop.index0 %} #note that index start at 0
            <tr>
            <td>★ {{ row }} {{ count }}</td>
            </tr>
         {% endif %} 
    {% endfor %}
{% endfor %}

这应该可以,但我还没有测试过;这大概就是这里的想法。您还可以通过阅读文档here来探索可能的情况

相关问题 更多 >