Jinja2块嵌套问题 [英] Jinja2 block nesting issue

查看:623
本文介绍了Jinja2块嵌套问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用 jinja2 作为模板语言。这里是简化的模板结构:

base.html :

  {%block content%} {%endblock%} 
{%block sidebar%} {%endblock%}


$ b

content.html

  {%extend' base.html'%} 

{%block content%}
< div class =content>
Content
{%block sidebar%}
< div class =sidebar>边栏< / div>
{%sidebar%}
< / div>
{%endblock%}

content.html render:

 < div class =content> 
Content
< div class =sidebar>边栏< / div>
< / div>
< div class =sidebar>边栏< / div>

如您所见,存在 sidebar 两次渲染 content.html



问题:

有没有办法避免出现<$在$ content 中留下侧边栏 {%block sidebar%} code> {%block content%} ?

解决方案

模板是无效的 - 你明确定位侧边栏相关的内容在内容块,所以它会在那里出现。此外,您的base.html似乎也是无效的,它应该看起来更像是:
$ b $ pre $%block%%{%endblock %}
{%block sidebar%} {%endblock%}


I am using jinja2 as a template language in my project. Here is simplified templates structure:

base.html:

{% block content %}{% endblock %}
{% block sidebar %}{% endblock %}

content.html:

{% extend 'base.html' %}

{% block content %}
    <div class="content">
        Content
        {% block sidebar %}
            <div class="sidebar">Sidebar</div>
        {% sidebar %}
    </div>
{% endblock %}

And the result of content.html render:

<div class="content">
    Content
    <div class="sidebar">Sidebar</div>
</div>
<div class="sidebar">Sidebar</div>

As you may see, sidebar is present twice at rendered content.html.

Question:

Is there a way to avoid appearance of the sidebar in content, leaving {% block sidebar %} inside {% block content %} ?

解决方案

I think your content.html template is invalid - you're clearly positioning sidebar related content inside the content block, so it will allways appear there. Also, your base.html seems invalid as well, it should look more like:

{% block content %}{% endblock %}
{% block sidebar %}{% endblock %}

这篇关于Jinja2块嵌套问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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