jinja2 - 如何在if语句中放置一个块? [英] jinja2 - how to put a block in an if statement?

查看:384
本文介绍了jinja2 - 如何在if语句中放置一个块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个base.html,它有一个默认的{{block block}%} %block content%}这个模板是扩展base.html.So我试过这个:

$ p $ {code> {%extendsbase.html %}
{%if condition == True%}
{%block content%}
< div>等等等等等等等等等等。
{%endblock content%}
{%endif%}

和i期待看到等等等等等等,如果条件是真实的,并看到默认的阻止,如果它是不正确的。



但是两次我得到了等等等等等等

然后我试过这个:

$ $ $ $ $ $ $扩展base.html%}
{%if condition == True%}
{%block content%}
< div>等等等等等等等等等等。
{%endblock content%}
{%else%}
{%block content%}
< div>默认事物< / div>
{%endblock content%}
{%endif%}

和I得到这个错误:

TemplateAssertionError:block'content'定义了两次

if语句?

解决方案

您不能创建 {%block%} 有条件的;一旦你使用标签,块就会被填充。

把你的条件放在块中,而使用 super()指示Jinja使用模板中定义的块的原始内容:

  {%extendsbase.html%} 
{%block content%}
{%if condition%}
< div>等等等等等等等等;
{%else%}
{{super()}}
{%endif%}
{%endblock content%}


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?

解决方案

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

这篇关于jinja2 - 如何在if语句中放置一个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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