【问题标题】:Get another app's templates in Django在 Django 中获取另一个应用程序的模板
【发布时间】:2010-12-23 01:09:41
【问题描述】:

这是我网站的结构:

mysite
    app_a
       templates
           a.html
    app_b
       templates
           b.html
       views.py

在views.py,我想得到a.html,

所以我用这个:

return render_to_response('app_a/a.html')

但它显示一个错误:

TemplateDoesNotExist 

我需要做什么?

【问题讨论】:

    标签: python django templates


    【解决方案1】:

    只需使用 render_to_response('a.html')

    假设你打开了默认的app目录模板加载器,问题是模板路径实际上是a.html

    所以在你当前的格式中,你应该写a.html 而不是app_a/a.html

    模板目录的推荐格式是

    mysite
        app_a
           templates
               app_a
                   a.html
        app_b
           templates
               app_b
                   b.html
           views.py
    
        global_templates
           app_b
                b.html
    

    这将适用于您的 app_a/a.html 示例

    推荐这种格式的原因是您可以根据每个应用程序合理地覆盖模板。

    如果所有文件都直接在应用程序模板目录中,您很容易得到冲突的模板名称。

    【讨论】:

      【解决方案2】:

      您可以在 settings.py 中指定一个 TEMPLATE_DIRS 变量,该变量是搜索模板的目录元组。如果您将两个应用程序中的模板目录添加到 TEMPLATE_DIRS,您应该没问题(只需注意搜索路径中的冲突)。

      【讨论】:

      • 例如,我的 templates/ 目录位于顶层(即所有应用程序之间共享)。在 settings.py 中,我像这样指示模板的位置: TEMPLATE_DIRS = (os.path.join(os.path.dirname(file), 'templates'),) ... 如果我想在搜索路径中添加更多模板目录,我会在逗号后附加其他路径。希望这会有所帮助!
      【解决方案3】:

      除了TEMPLATE_DIRS 设置,尝试将django.template.loaders.app_directories.Loader 添加到TEMPLATE_LOADERS 设置,因为这将使INSTALLED_APPS 中的应用程序的所有模板都可用。这样您就不需要将它们全部放在一个主目录下。

      见Django Documentation for template loaders

      【讨论】:

        猜你喜欢
        • 2018-03-24
        • 2016-03-15
        • 1970-01-01
        • 1970-01-01
        • 2011-06-02
        • 2013-10-01
        • 2021-03-28
        • 1970-01-01
        • 2019-07-10
        相关资源
        最近更新 更多