django模板:包含和扩展 [英] django templates: include and extends

查看:148
本文介绍了django模板:包含和扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



所以我试图这样做:



page1.html:

  {%extendsbase1.html%} 
{%includecommondata.html%}

page2.html:

  {%扩展base2.html%} 
{%includecommondata.html%}

问题是我似乎不能同时使用extend和include。有办法吗?如果没有,我如何完成上述?



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



这样做的目的是以pdf格式和HTML格式提供相同的页面,其格式略有不同。上述问题虽然简化了我想要做的事情,但如果我能得到一个解决问题的答案。

解决方案

p>当您使用扩展模板标签时,您说的是当前模板扩展了另一个模板 - 它是一个子模板,取决于父模板。 Django将查看您的子模板并使用其内容填充父级。



您想在子模板中使用的所有内容都应该在Django用于填充父母如果要在该子模板中使用include语句,则必须将其放在一个块中,以使Django有意义。否则它只是没有意义,Django不知道该怎么做。



Django文档有一些很好的例子,使用块来替换块在父模板中。



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


I would like to provide the same content inside 2 different base files.

So I'm trying to do this:

page1.html:

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

page2.html:

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

The problem is that I can't seem to use both extends and include. Is there some way to do that? And if not, how can I accomplish the above?

commondata.html overrides a block that is specified in both base1.html and base2.html

The purpose of this is to provide the same page in both pdf and html format, where the formatting is slightly different. The above question though simplifies what I'm trying to do so if I can get an answer to that it will solve my problem.

解决方案

When you use the extends template tag, you're saying that the current template extends another -- that it is a child template, dependent on a parent template. Django will look at your child template and use its content to populate the parent.

Everything that you want to use in a child template should be within blocks, which Django uses to populate the parent. If you want use an include statement in that child template, you have to put it within a block, for Django to make sense of it. Otherwise it just doesn't make sense and Django doesn't know what to do with it.

The Django documentation has a few really good examples of using blocks to replace blocks in the parent template.

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

这篇关于django模板:包含和扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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