Python jinja2 - 如何在 if 语句中放置一个块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22655031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:22:16  来源:igfitidea点击:

jinja2 - how to put a block in an if statement?

pythonpython-2.7if-statementflaskjinja2

提问by Taxellool

I am trying to use an ifto determine which block should fill my {% block content %}.

我正在尝试使用 anif来确定哪个块应该填充我的{% block content %}.

I have a base.htmlwhich has a default {% block content %}and this template is extending base.html. So I tried this:

我有一个base.html具有默认值的{% block content %}模板,并且该模板正在扩展base.html. 所以我试过这个:

{% extends "base.html" %}
{% if condition == True %}
    {% block content %}
    <div>blah blah blah blah</div>
    {% endblock content %}
{% endif %}

and I was expecting to see blah blah blah blahif condition was true and see the default block if it wasn't true.

我期待查看blah blah blah blah条件是否为真,如果不为真,则查看默认块。

But both times I got blah blah blah blah.

但两次我都得到了blah blah blah blah

Then I tried this one:

然后我尝试了这个:

{% extends "base.html" %}
{% if condition == True %}
    {% block content %}
    <div>blah blah blah blah</div>
    {% endblock content %}
{% else %}
    {% block content %}
    <div>The Default Thing</div>
    {% endblock content %}
{% endif %}

and I got this error:

我收到了这个错误:

TemplateAssertionError: block 'content' defined twice

How can I put a block inside an ifstatement?

如何在if语句中放置一个块?

采纳答案by Martijn Pieters

You cannot make a {% block %}conditional; once you use the tag, the block is always going to be filled in.

你不能{% block %}有条件;一旦你使用了这个标签,这个块总是会被填满。

Put your conditional insidethe block instead, and use super()to instruct Jinja to use the original contents of the block as defined in the template:

将您的条件放在块中,并用于super()指示 Jinja 使用模板中定义的块的原始内容:

{% extends "base.html" %}
{% block content %}
    {% if condition %}
        <div>blah blah blah blah</div>
    {% else %}
        {{ super() }}
    {% endif %}
{% endblock content %}