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

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

问题描述

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

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

所以我正在尝试这样做:

So I'm trying to do this:

page1.html:

page1.html:

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

page2.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 覆盖在 base1.html 和 base2.html 中指定的块

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

这样做的目的是提供pdf和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.

推荐答案

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

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.

您想在子模板中使用的所有内容都应该在块内,Django 使用块来填充父模板.如果您想在该子模板中使用 include 语句,您必须将它放在一个块中,以便 Django 理解它.否则它就是没有意义,Django 不知道如何处理它.

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.

Django 文档中有一些非常好的示例,它们使用块替换父模板中的块.

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天全站免登陆