Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

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

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

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 %}

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

But both times I got 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 if statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...