本文介绍了在Jinja for循环中嵌套if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个Jinja模板的循环中潜入if语句:

I am trying to sneak in an ifstatement within a loop for a jinja template:

</table>
<class="container">
<table border ="1">
<caption> BBOXX <caption>
<thead class="thead-inverse">
    <tr>
        <th>CU Serial</th>
        <th>System</th>
        <th>Version</th>
        <th>Enable Status</th>
    </tr>
        {% for d in client_data %}
        <tr>
            <td>{{ d["serial_number"]}} </td>
            <td>{{ d["hardware_type"]}} </td>
                {% if {{ d["current_enable_flag"]}} == TRUE %}
                    <td> {{ON}} </td>
                {% else %}
                    <td> {{OFF}} </td>
                {% endif %}
        </tr>
        {% endfor %}
</table>

错误是TemplateSyntaxError: expected token ':', got '}'

:应该在哪里?

推荐答案

您的if语法错误.您无需使用{{ ... }}插入变量,仅用于在模板输出中插入值.

You have your if syntax wrong. You do not need to use {{ ... }} to insert a variable, that's only used to interpolate values in the template output.

使用

{% if d["current_enable_flag"] == TRUE %}
    <td> {{ON}} </td>
{% else %}
    <td> {{OFF}} </td>
{% endif %}

如果d["current_enable_flag"]是Python布尔值,则可以完全删除== TRUE部分.

If d["current_enable_flag"] is a Python boolean, you can drop the == TRUE part altogether.

演示:

>>> from jinja2 import Template
>>> template = Template('''\
... {% for d in client_data %}
... <tr>
...     <td>{{ d["serial_number"]}} </td>
...     <td>{{ d["hardware_type"]}} </td>
...     {% if d["current_enable_flag"] %}
...         <td> {{ON}} </td>
...     {% else %}
...         <td> {{OFF}} </td>
...     {% endif %}
... </tr>
... {% endfor %}
... ''')
>>> html_rendered = template.render(client_data=[
...     {'serial_number': 42, 'hardware_type': 'foo', 'current_enable_flag': True},
...     {'serial_number': 81, 'hardware_type': 'bar', 'current_enable_flag': False}
... ], ON='ON', OFF='OFF')
>>> print(html_rendered)

<tr>
    <td>42 </td>
    <td>foo </td>

        <td> ON </td>

</tr>

<tr>
    <td>81 </td>
    <td>bar </td>

        <td> OFF </td>

</tr>

这篇关于在Jinja for循环中嵌套if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:25