【问题标题】:How to have nested base.html in django's templates?如何在 django 模板中嵌套 base.html?
【发布时间】:2017-08-05 10:58:58
【问题描述】:

我正在重建我的所有模板,使其变得更易于管理和自定义,树看起来像这样:

├───core
│   └───templates
│       └───base.html (original, touches every page)
│   ...   
│
├───app1
│   └───templates
│       ├───base.html (extends from core/base.html, only touches app1)
│       └───file1.html (extends from app1/base.html)
│   ...
│
└───app2
    └───templates
        ├───base.html (extends from core/base.html, only touches app2)
        └───file2.html (extends from app2/base.html)
    ...

要将app1 的模板连接到core 的模板,我使用{% extends '../../core/templates/base.html' %},在核心应用程序中会有{% block container %}{% endblock %} 作为示例,在app1、app2 中会有其他{% block other_content %}{% endblock %} 块.如您所见,块也是嵌套的。

问题是我收到了这个错误:

相对路径“../../core/templates/base.html”指向模板“base.html”所在的文件层次结构之外。

问题:我想知道在不进行硬编码的情况下解决此问题的最佳方法是什么?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    原来的base.html与其他同类有冲突,所以我将app1app2的基础改名为base[app_name].html,解决了我的问题。树看起来像这样:

    ├───core
    │   └───templates
    │       └───base.html (original, touches every page)
    │   ...   
    │
    ├───app1
    │   └───templates
    │       ├───base_app1.html (extends from core/base.html, only touches app1)
    │       └───file1.html (extends from app1/base_app1.html)
    │   ...
    │
    └───app2
        └───templates
            ├───base_app2.html (extends from core/base.html, only touches app2)
            └───file2.html (extends from app2/base_app2.html)
        ...
    

    也不需要硬编码路径:{% extends 'base.html' %} 就足够了,{% extends 'base_[app_name].html' %} 用于应用模板中的文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 2016-07-12
      • 2013-08-01
      • 1970-01-01
      • 2011-08-20
      • 2010-12-26
      • 2016-06-11
      相关资源
      最近更新 更多