Jinja2 Inheritance with Blocks and Includes

我怕爱的太早我们不能终老 提交于 2019-12-03 11:19:36

问题


I can't figure out how to modify blocks from included templates using Jinja2. Here's an example where I use three files.

base.html:

<html>{% include "content.html" %}</html>

content.html:

<h1>{% block title %}Title{% endblock title%}</h1>
<div>{% block content_body %}Content Body{% endblock content_body%}</div>

story.html

{% extends "base.html" %}
{% block title %}story.title{% endblock title %}
{% block content_body %}story.description{% endblock content_body %}

When rendering story.html, I'll get:

<html>
<h1>Title</h1>
<div>Content Body</div>
</html>

How would I render with the expected values?


回答1:


base.html is not rendered because it's not invoked by any template. What you could do is a second level of extension:

base.html:

<html>{% block html %}{% endblock %}</html>

content.html:

{% extends "base.html" %}
{% block html %}
<h1>{% block title %}Title{% endblock title%}</h1>
<div>{% block content_body %}Content Body{% endblock content_body%}</div>
{% endblock %}

Still, that is probably overkill, you will likely find that a single base template is enough (i.e. combine base.html and content.html into a single template).



来源:https://stackoverflow.com/questions/9245708/jinja2-inheritance-with-blocks-and-includes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!