简体   繁体   English

Jinja2 - 如何使用带有自定义 Jinja2 过滤器的“for”循环?

[英]Jinja2 - How to use 'for' loops with a custom Jinja2 filter?

In my HTML, I have imported import itertools to iterate over two Python "tables" simultaneously.在我的 HTML 中,我导入了import itertools以同时迭代两个 Python“表”。 I do this as the position of elements from one "table" directly relate to the position of elements from the other.我这样做是因为一个“表格”中元素的位置与另一个“表格”中元素的位置直接相关。

My HTML-Jinja2 Template:我的 HTML-Jinja2 模板:

    {% macro zip_longest() %}
        {% for rows, rows2 in zip_longest(table, table2) %}
    
        <tr style="vertical-align: middle;">
            <td width=15%> {{ rows[0] }} </td>
            <td width=20%><div style="height: 49px; overflow: auto;">{{rows[1]}}</div></td>
            <td width=15%> {{ rows[2] }} </td>
            <td><div> {{ rows[3] }} </div><div>Serving Size: {{ rows[4] }}</div></td>
            <td style=""><button id="button{{rows[0]}}" type="button" class="button btn btn-secondary" style="background-color: #5C666E; outline: none; border: none;"> Nutrition </button> </td>
        </tr>
        <tr>
            <td colspan="5" id="info{{rows[0]}}" style="background-color: #5C666E; color: white; display: none;"> Nutrient Information {{ rows2[0] }} </td>
            <td style="display: none;">Energy</td>
        </tr>
     {% endfor %}
   {% endmacro %}

The result of using zip_longest from itertools does not cause an Internal server error and does in fact display the table headers.使用itertools中的zip_longest的结果不会导致内部服务器错误,并且实际上会显示表头。 However, any python variables ({{ rows[4] }}, etc) are not displayed.但是,不会显示任何 Python 变量({{ rows[4] }} 等)。

Here is the relevant Python:这是相关的Python:

from itertools import zip_longest
...
app.jinja_env.filters["zip_longest"] = zip_longest
...
return render_template("homepage.html", table=table, table2=table2)

我猜:您必须将宏{% macro zip_longest() %}重命名为其他名称,例如: {% macro m__zip_longest() %}以避免与函数名称zip_longest()本身发生冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM