Django模板:包含和扩展

2024-09-28 23:17:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在两个不同的基本文件中提供相同的内容。

所以我试着这么做:

第1页.html:

{% extends "base1.html" %}
{% include "commondata.html" %}

第2页.html:

{% extends "base2.html" %} 
{% include "commondata.html" %}

问题是我似乎不能同时使用extends和include。有办法吗?如果没有,我怎么能做到以上这些呢?

commondata.html覆盖base1.html和base2.html中指定的块

这样做的目的是以pdf和html格式提供相同的页面,其中的格式略有不同。不过,上面的问题简化了我想做的事情,如果我能得到答案的话,它会解决我的问题。


Tags: 文件答案目的内容pdfincludehtml格式
3条回答

使用extends template标记时,您是说当前模板扩展了另一个模板——它是一个子模板,依赖于父模板。Django将查看子模板并使用其内容填充父模板。

要在子模板中使用的所有内容都应该在块中,Django使用这些块来填充父模板。如果要在该子模板中使用include语句,则必须将其放在块中,以便Django能够理解它。否则就没有意义了,Django也不知道该怎么办。

Django文档中有几个使用块替换父模板中的块的非常好的例子。

https://docs.djangoproject.com/en/dev/ref/templates/language/#template-inheritance

来自Django docs:

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

因此Django不会从commondata.html中获取任何块,也不知道如何处理块外呈现的html。

这应该能帮你做到:把include标签放在一个块区域内。

第1页.html:

{% extends "base1.html" %}

{% block foo %}
   {% include "commondata.html" %}
{% endblock %}

第2页.html:

{% extends "base2.html" %}

{% block bar %}
   {% include "commondata.html" %}
{% endblock %}

相关问题 更多 >