【问题标题】:Use the template of another django app in an another app在另一个应用程序中使用另一个 django 应用程序的模板
【发布时间】:2018-03-24 00:43:27
【问题描述】:

我有两个 django 应用程序。一个属于核心代码,一个属于贡献应用程序。我需要做的是在我的 contrib 应用程序中显示一个模板,该模板实际上已经存在于核心应用程序中。这或多或少是文件夹结构:

  • django 项目
    • 核心应用
      • 模板 ...
    • 贡献应用程序
      • 模板 -template_from_core_app

模板呈现来自核心应用程序中存在的视图和表单的数据。我想知道做这样的事情的最好方法是什么。

【问题讨论】:

  • 这里不应该有任何问题:模板不以任何方式“属于”应用程序,除了位于其文件目录中。

标签: python django templates


【解决方案1】:

是的,你可以这样做,使用 include

core_app/
    templates/
        core_app/
            page1.html
contrib_app/
    templates/
        contrib_app/
            page1.html
            page2.html

{% include "core_app/page1.html" %} or {% include "contrib_app/page1.html" %}

也可以参考这篇文档Template

【讨论】:

  • 为了避免名称冲突,这就是为什么在templates中使用相同的名称
【解决方案2】:

鉴于您在 contrib.views 中使用了 render() 快捷方式,您只需从核心应用程序加载模板并确保上下文变量满足核心模板呈现的内容。如果您提供“coreapp/template.html”之类的路径,get_context() 模板加载器后端会在正确设置的情况下找到正确的模板:

settings.py: 在TEMPLATE 字典中设置APP_DIRS=True。 Django 将通过 get_template() 和 select_template() 函数在每个应用程序中查找模板。

contrib.views.py

from django.http import HttpResponse
from django.template import loader

def index(request):
    ...
    template = loader.get_template('coreapp/template.html')
    context = {
        'core_template_var': core_template_var,
        ...
    }
    return HttpResponse(template.render(context, request))

推荐阅读:

渲染():https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#render

模板加载:https://docs.djangoproject.com/en/1.11/topics/templates/#template-loading

注意:您也可以使用带有 select_template() 而不是 get_template() 的备用模板。 select_template() 获取一个列表并依次尝试每个模板路径,返回第一个确实存在的路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2011-12-22
    • 2011-06-02
    • 2013-10-01
    • 2010-09-24
    • 1970-01-01
    相关资源
    最近更新 更多