django包含其他应用程序的模板 [英] django include template from another app

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

问题描述

在设置我的项目并努力使应用程序不依赖时,我遇到了一个障碍。我希望来自不同应用程序的所有模板都具有一致的页眉和页脚。这是我正在尝试的:

While setting up my project and working to keep apps non-dependent, I've hit a snag. I'd like all of the templates from the different apps to have a consistent header and footer. Here's what I'm trying:

myproject/
         base/
             templates/
                      header.html
                      footer.html
         app1/
             templates/
                      my_app1_page.html -> want to include 'header.html'
                                           and 'footer.html' from base app

假装还有更多的应用程序也希望这样做。这是可能的和/或正确的方法吗?

Pretend there are many more apps that want to do this as well. Is this possible and/or the right way to do it?

推荐答案

只要应用程序在INSTALLED_APPS和模板加载器对于应用程序dirs启用,您可以添加来自其他应用程序的任何模板,即:

As long as the apps are in INSTALLED_APPS and the template loader for apps dirs is enabled, you can include any template from another app, i.e.:

{% include "header.html" %}

...因为您的模板直接位于应用程序的模板目录中。
一般来说,为避免名称冲突,最好使用:

... since your templates are located directly in the templates dir of your app. Generally, in order to avoid name clashes it is better to use:

app1/
    templates/
        app1/
            page1.html
            page2.html
app2/
    templates/
        app2/
            page1.html
            page2.html

{%includeapp1 / page1.html%} {%includeapp2 / page1.html%} ...

:为了保持一致的外观和感觉,使用模板继承而不是包含更好。模板继承是Django模板系统的非常好的东西之一,选择继承(包括大多数时候)。

But: for keeping a consistent look and feel, it is so much better to use template inheritance rather than inclusion. Template inheritance is one of the really good things of the Django template system, choose inheritance over inclusion whenever it makes sense (most of the time).

我的建议:


  • 为您的项目提供基本模板(base.html是默认约定),带页眉和页脚,您的主要内容的 {%block content%}

  • 让您的其他模板继承自base.html {%extendsbase.html%} 并覆盖内容部分

  • Have a base template for your project ("base.html" is the default convention) with header and footer and a {%block content%} for your main content.
  • Have your other templates inherit form base.html {% extends "base.html" %} and override the content section

查看另一个响应此问题链接到文档

See another response to this question for links to the doc

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

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