【问题标题】:Is it possible to extend a site-wide template in Django / refer to templates in higher directories?是否可以在 Django 中扩展站点范围的模板/引用更高目录中的模板?
【发布时间】:2018-12-12 06:10:32
【问题描述】:

我希望有一个贯穿整个网站的页眉/页脚。目前,我有一个位于应用程序 (project/app1/templates/app/base.html) 中的 base.html 文件,并希望应用一个可以在整个站点中使用的 html 模板。这是可能的还是模板只能在应用模板文件夹中引用?我可以将模板放在更高的目录中,例如 project/template/base.html 或 project/base.html 并调用它,这样我就不必将相同的模板复制并粘贴到每个应用程序模板文件夹中吗?

【问题讨论】:

    标签: django


    【解决方案1】:

    我们可以为项目使用根“模板”目录。

    settings.py

    import os
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                # ... some options here ...
            },
        },
    ]
    

    项目结构

    └── MY_PROJECT
    └── BASE_DIR
        ├── my_proj
        │   └── settings.py
        ├── manage.py
        └── templates
    

    更多信息请阅读:https://learnbatta.com/blog/understanding-django-project-structure-26/

    【讨论】:

    • 感谢您的成功。但是,展望未来,我是否必须在我的应用模板 html 文件中具体说明?例如,如果我在 project/app/templates/app 中有以下代码:'{% extends "base.html" %} {% block content %} {% endblock content %}' 为了使用模板 w/在 app/templates/app 中,我必须用 app/templates/app/appbase.html 替换 base.html?
    • @HelloColorClear 不,您不需要这样做。 {% extends "base.html" %} 应该可以工作。
    猜你喜欢
    • 2013-01-24
    • 2013-06-13
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2010-11-27
    • 1970-01-01
    相关资源
    最近更新 更多