使用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
的情况下渲染它?
答案 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将负责包含父模板中的块内容。