Jinja2模板继承

时间:2015-10-20 21:03:54

标签: python flask jinja2

使用Jinja2,是否需要在所有其他模板扩展的基本模板中定义所有块?例如,给定以下模板:

<-- ultra_base.j2 -->
<head> 
</head>
<body>
  {% block content %}{% endblock %}
  {% block extra_js %} {% endblock %}
</body>

<-- child.j2 -->
{% extends ultra_base %}

{% block extra_js %}
  <script src="somefile.js"> 
{% endblock %}

{% block page_js %} {% endblock %}

<-- grandchild.j2 -->
{% extends child %}

{% block content %} 
<h2> Grandchild Content </h2>
{% endblock content %} 

{% block page_js %}
<script src="grandchild.js"></script>
{% endblock page_js %}

永远不会呈现page_js块。有没有办法在不改变ultra_base的情况下渲染它?

2 个答案:

答案 0 :(得分:2)

您可以将page_js放在{% block page_js %} {% endblock %}中的extra_js块内来呈现child.j2

<-- child.j2 -->
{% extends ultra_base %}

{% block extra_js %}
    <script src="somefile.js"> 
    {% block page_js %} 
    {% endblock %}
{% endblock %}

答案 1 :(得分:2)

问题是page_js中的child.j2阻止了#34;在不知名的地方&#34;,它不会改变ulta_base.j2的任何阻止,所以Jinja2不会渲染任何东西。解决方案非常简单,您甚至不需要定义新的extra_js块,只需使用Jinja2的super()函数:

ultra_base.j2保持不变:

<!-- ultra_base.j2 -->
<head> 
</head>
<body>
  {% block content %}{% endblock %}
  {% block extra_js %} {% endblock %}
</body>

child.j2模板:

<!-- child.j2 -->
{% extends ultra_base %}

{% block extra_js %}
  {{ super() }}
  <script src="somefile.js"></script>
{% endblock %}

grandchildj2

<!-- grandchild.j2 -->
{% extends child %}

{% block content %} 
<h2> Grandchild Content </h2>
{% endblock content %} 

{% block extra_js %}
  {{ super() }}
  <script src="grandchild.js"></script>
{% endblock extra_js %}

Jinja2将负责包含父模板中的块内容。