Django View - 首先从调用应用程序的目录加载模板

标签 django templates

我尝试在我的 HTML 模板上保持某种程度上一致的命名方案。 IE。 index.html 用于主页面,delete.html 用于删除页面等等。但是 app_directories 加载器似乎总是从按字母顺序排列的第一个应用加载模板。

有什么方法可以始终首先检查调用应用程序的 templates 目录中的匹配项?

我的settings.py中的相关设置:

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

TEMPLATE_LOADERS = (
    'django.template.loaders.app_directories.load_template_source',
    'django.template.loaders.filesystem.load_template_source',
)
TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH, 'templates'),
)

我已经尝试更改 TEMPLATE_LOADERS 的顺序,但没有成功。


根据 Ashok 的要求进行编辑:

每个应用的目录结构:

templates/
    index.html
    add.html
    delete.html
    create.html
models.py
test.py
admin.py
views.py

在每个应用的 views.py 中:

def index(request):
    # code...
    return render_to_response('index.html', locals())

def add(request):
    # code...
    return render_to_response('add.html', locals())

def delete(request):
    # code...
    return render_to_response('delete.html', locals())

def update(request):
    # code...
    return render_to_response('update.html', locals())

最佳答案

这是因为 app_directories 加载器本质上与将每个应用程序的模板文件夹添加到 TEMPLATE_DIRS 设置相同,例如喜欢

TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH, 'app1', 'templates'),
    os.path.join(PROJECT_PATH, 'app2', 'template'),
    ...
    os.path.join(PROJECT_PATH, 'templates'),
)

问题在于,正如您所提到的,index.html 将始终位于 app1/templates/index.html 而不是任何其他应用程序中。如果不修改 app_directories 加载器并使用内省(introspection)或传递应用程序信息,没有简单的解决方案可以神奇地修复此行为,这会变得有点复杂。更简单的解决方案:

  • 保持你的 settings.py 不变
  • 在每个应用程序的模板文件夹中使用应用程序的名称添加一个子目录
  • 在“app1/index.html”或“app2/index.html”等 View 中使用模板

更具体的例子:

project
    app1
        templates
            app1
                index.html
                add.html
                ...
        models.py
        views.py
        ...
    app2
        ...

然后在 View 中:

def index(request):
    return render_to_response('app1/index.html', locals())

您甚至可以编写一个包装器来自动将应用程序名称添加到您的所有 View 中,甚至可以扩展为使用内省(introspection),例如:

def render(template, data=None):
    return render_to_response(__name__.split(".")[-2] + '/' + template, data)

def index(request):
    return render('index.html', locals())

_____name_____.split(".")[-2] 假设文件在一个包中,所以它将变成例如'app1.views' 到 'app1' 以添加到模板名称。这还假设用户永远不会在不重命名模板目录中的文件夹的情况下重命名您的应用程序,这可能不是一个安全的假设,在这种情况下,只需对模板目录中的文件夹名称进行硬编码。

关于Django View - 首先从调用应用程序的目录加载模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3092865/

相关文章:

django - 如何将 Django 中 Count() 的输出转换为 Django 1.8 中的 FloatField

python - Django def __str__ 列表索引超出范围

c++ - 根据参数返回类型

c++ - 使用可变参数模板进行隐式转换

python - 如何在 Django 模板中正确列化表格

python - 如何在相同的数据上使用 Django for 循环两次

c++ - 无法将模板函数作为回调参数传递

c++ - CRTP、cpp 文件中的前向声明和模板

c++ - 如何在 C++ 中实现允许许多未定义数据类型参数的递归函数模板?

django - 用户未传递到模板 TEMPLATE_CONTEXT_PROCESSORS