【问题标题】:Django templates inheritance between apps应用程序之间的 Django 模板继承
【发布时间】:2017-08-02 18:25:41
【问题描述】:

在 Django 模板中,extends 标签使用类似于{% extends "base.html" %}

如果可能的话,我希望在多个应用中为模板命名相同(例如 templates/bookkeeping/bookkeeping.html)。

我希望更专业的应用程序(处理特定项目的簿记)使用extends 在不那么专业的应用程序(处理我们的几个项目的常见簿记任务)中扩展模板。特别是在不太专业的应用程序中,我创建了一个没有太多设计的模板。在更专业的应用程序中,我想呈现相同的信息,但具有特定的设计(CSS 等)

在 Django 1.11 中可以对此做些什么?

如果无法使用具有相同模板名称(但不同应用程序)的模板扩展,还有什么其他可能的方法来解决这个问题?我可以检查derived.html 是否存在,如果没有derived.html,则回退到base.html,但这会导致编写乏味的Python 代码。有没有更好的办法?

【问题讨论】:

  • 你有没有解决过这个@porton?我对 Django 3.X 有同样的目标。

标签: django django-templates django-apps


【解决方案1】:

您能否将每个应用程序中的模板目录命名如下:

app1/templates/app1/bookkeeping/bookkeeping.html
app2/templates/app2/bookkeeping/bookkeeping.html

然后在更专业的应用程序(app2)中使用:

{% extends "app1/bookkeeping/bookkeeping.html" %}

或者我在这里遗漏了什么?

编辑:

您可以链接您的 Python 代码以指向一个模板,例如 templates/pages/bookeeping_base.html。在该模板中,您可以说:

{% if project.is_specialised %}
    {% include 'app2/bookkeeping/bookkeeping.html' %}
{% else %}
    {% include 'app1/bookkeeping/bookkeeping.html' %}
{% endif %}

那么如上所述,app2 模板仍然可以扩展 app1 模板。

【讨论】:

  • 那么我的 Python 代码中需要不同的模板路径:有时是 app1/bookkeeping/bookkeeping.html,有时是 app2/bookkeeping/bookkeeping.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 2010-12-23
  • 2021-12-10
  • 1970-01-01
  • 2015-09-06
  • 2011-02-04
相关资源
最近更新 更多