简体   繁体   中英

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. 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:

    {% 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. However, any python variables ({{ rows[4] }}, etc) are not displayed.

Here is the relevant 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()本身发生冲突。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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