在 Tornado 模板中使用 if 语句进行循环。可能吗?

For loop with if statement in Tornado template. Is it possible?

这是我的模板标记中的一些片段:

{% for filename, uuid, i in files %}
    <div class="content">
        {% if i == 0 %}
            {% for filename, uuid, name in nginx %}
                <span id="{{ uuid }}" class="{{ name }}">{{ filename }}</span>
                <div id="{{ uuid }}" class="{{ name }}">
        {% elif i == 2 %}
            {% for filename, uuid, name in apache %}
                <span id="{{ uuid }}" class="{{ name }}">{{ filename }}</span>
                <div id="{{ uuid }}" class="{{ name }}">
{% end %}

这是来自服务器端的:

class MainHandler(RequestHandler):
    @asynchronous
    def get(self, *args, **kwargs):

        names = ['Nginx', 'Apache']
        files = [(n, file_uuid(f), i) for n, f, i in zip(names, FILENAMES, range(len(FILENAMES)))]
        nginx = [(op.basename(f), file_uuid(f), 'nginx') for f in NGINX]
        httpd = [(op.basename(f), file_uuid(f), 'apache') for f in HTTPD]
        kwargs = {
            'hostname': self.request.host,
            'files': files,
            'nginx': nginx,
            'apache': httpd,
        }
        self.render('template.html', **kwargs)

我的列表中有不同数量的文件,nginx 和 apache,我愿意将它们放在不同的选项卡上。

但是龙卷风说的是:

File "/usr/lib64/python2.7/site-packages/tornado/template.py", line 837, in _parse
block_body = _parse(reader, template, operator, operator)
File "/usr/lib64/python2.7/site-packages/tornado/template.py", line 789, in _parse
raise ParseError("%s block cannot be attached to %s block" % (operator, in_block))
ParseError: elif block cannot be attached to for block

根据Tornado docs,有for with continue/break and if/elif/else支持,但是 tornado 模板中是否支持 for loop + if 语句? 如果没有,我可以通过什么方式实现我的目的?

在模板中,缩进并不重要,因此您必须在每个复合语句后使用 {% end %} 标记:

{% for filename, uuid, i in files %}
<div class="content">
    {% if i == 0 %}
        {% for filename, uuid, name in nginx %}
            <span id="{{ uuid }}" class="{{ name }}">{{ filename }}</span>
            <div id="{{ uuid }}" class="{{ name }}">
        {% end %}
    {% elif i == 2 %}
        {% for filename, uuid, name in apache %}
            <span id="{{ uuid }}" class="{{ name }}">{{ filename }}</span>
            <div id="{{ uuid }}" class="{{ name }}">
        {% end %}
    {% end %}
{% end %}

请注意,在 if/elif 的情况下,您只需要在最后一个 elif 之后添加一个 end;不要在 if 和它的 elif 之间放置 end