Jinja2模板-for循环 [英] Jinja2 Template - for loop

查看:97
本文介绍了Jinja2模板-for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到另一个存在类似问题的帖子,我正在尝试生成一些带有flask和wtforms的复选框,此刻我已经获得了这段代码:

didn't find another post which has the similar problem, I'm trying to generate some checkboxes with flask and wtforms, at the moment I've got this piece of code:

<div class="control-group">
    <p><strong>Check the enabled BRI Ports</strong></p>
    <label class="checkbox inline">
        {{ form.bri1(value=1) }} {{ form.bri1.label }}
    </label>
    <label class="checkbox inline">
        {{ form.bri2(value=1) }} {{ form.bri2.label }}
    </label>
    <label class="checkbox inline">
        {{ form.bri3(value=1) }} {{ form.bri3.label }}
    </label>
    <label class="checkbox inline">
        {{ form.bri4(value=1) }} {{ form.bri4.label }}
    </label>
</div>

到目前为止,该方法仍然有效,但是现在我尝试使用一个简单的for循环来完成此操作:

This works so far, but now I try to do this with a simple for-loop like:

<div class="control-group">
    <p><strong>Check the enabled BRI Ports</strong></p>
    {% for n in range(1,6) %}
    <label class="checkbox inline">
        {{ form.brin.label }}
    {% endfor %}
</div>

我尝试过使用(),{}和{{}} ...甚至有可能吗?

I tried with (), {} and {{}} ... is this even possible?

推荐答案

尝试:

<div class="control-group">
    <p><strong>Check the enabled BRI Ports</strong></p>
    {% for name, field in form._fields.items() %}
        {% if name != 'csrf_token' %}
            <label class="checkbox inline">
                {{ field(value=1) }} {{ field.label }}
            </label>
        {% endif %}
    {% endfor %}
</div>

您可以在其中设置排序(form._fields.items())或条件({% if name != 'csrf_token' %}).或者:

There you can set sorting instead form._fields.items() or condition instead {% if name != 'csrf_token' %}. Or:

<div class="control-group">
    <p><strong>Check the enabled BRI Ports</strong></p>
    {% for n in range(1,6) %}
        {% if form['bri' + n|string] %}
            <label class="checkbox inline">
                {{ form['bri' + n|string](value=1) }} {{ form['bri' + n|string].label }}
            </label>
        {% endif %}
    {% endfor %}
</div>

您还可以使用n.__str__()代替过滤器n|string.

There you can also use n.__str__() instead filter n|string.

这篇关于Jinja2模板-for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆