jinja2 - 如何在 if 语句中放置一个块? [英] jinja2 - how to put a block in an if statement?
问题描述
我正在尝试使用 if
来确定哪个块应该填充我的 {% block content %}
.
I am trying to use an if
to determine which block should fill my {% block content %}
.
我有一个 base.html
,它有一个默认的 {% block content %}
并且这个模板正在扩展 base.html
.所以我尝试了这个:
I have a base.html
which has a default {% block content %}
and this template is extending base.html
. So I tried this:
{% extends "base.html" %}
{% if condition == True %}
{% block content %}
<div>blah blah blah blah</div>
{% endblock content %}
{% endif %}
并且我期待看到 blah blah blah blah
如果条件为真,则看到默认块如果不为真.
and I was expecting to see blah blah blah blah
if condition was true and see the default block if it wasn't true.
但两次我都得到了blah blah blah blah
.
然后我尝试了这个:
{% 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 %}
我收到了这个错误:
TemplateAssertionError: block 'content' defined twice
如何在 if
语句中放置一个块?
How can I put a block inside an if
statement?
推荐答案
您不能使 {% block %}
成为条件;一旦你使用了这个标签,这个块总是会被填满.
You cannot make a {% block %}
conditional; once you use the tag, the block is always going to be filled in.
把你的条件放在块中,并使用super()
来指示Jinja使用模板中定义的块的原始内容:
Put your conditional inside the block instead, and use super()
to instruct Jinja to use the original contents of the block as defined in the template:
{% extends "base.html" %}
{% block content %}
{% if condition %}
<div>blah blah blah blah</div>
{% else %}
{{ super() }}
{% endif %}
{% endblock content %}
这篇关于jinja2 - 如何在 if 语句中放置一个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!