我试图在我的HTML模板上保持某种程度上一致的命名方案.即主页面的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'),
)

我try 过改变TEMPLATE_LOADERS的顺序,但没有成功.


Edit as requested by Ashok:

每个应用程序的目录 struct :

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_目录加载器本质上与将每个app的模板文件夹添加到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/plates/index.html中,而不是任何其他应用程序中.如果不修改APP_DIRECTORIES加载器并使用自省或传递应用程序信息(这会变得有点复杂),就不会有简单的解决方案来神奇地修复此行为.更简单的解决方案:

  • 保留你的设置.就像现在一样
  • 在每个应用程序的Templates文件夹中添加一个带有应用程序名称的子目录
  • 在诸如"app1/index.html"或"app2/index.html"之类的视图中使用模板

有关更具体的示例:

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

然后在视图中:

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

您甚至可以编写一个包装器来自动将应用程序名称预先添加到您的所有视图中,甚至可以将其扩展为使用自省,例如:

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

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

_name_.plit(".")[-2]假定文件在包中,因此它会将例如‘app1.views’转换为‘app1’,以作为模板名称的前缀.这还假设用户永远不会在不重命名Templates目录中的文件夹的情况下重命名您的应用程序,这可能不是一个安全的假设,在这种情况下,只需硬编码Templates目录中的文件夹名称即可.

Django相关问答推荐

如何使用Django';S生成的字段来统计相关对象?

Django Prefetch上的多重过滤

Django 中模型将数据存储在哪里?

有没有办法在Django中按需/点击仅获取和序列化一部分数据以提高性能?

无法创建超级用户,因为 Django 中的一列(外键)不能为空

如何计算 Django 模型中特定对象的数量?

Django ORM 查询优化问题

django 在 ubuntu 中安装在哪里

如何测试某个日志(log)消息是否记录在 Django 测试用例中?

在基于类的通用视图 CreateView 中访问 request.user 以便在 Django 中设置 FK 字段

Django - 如何从模型中 Select 特定列?

如何在Django中获取一个组的所有用户?

jinja2模板引擎中的这个-是做什么的?

整数的Python正则表达式?

在 django 中是否有生成 settings.SECRET_KEY 的功能?

django python 日期时间设置为午夜

如何在 django 中捕获UNIQUE constraint failed404

ModelForm 上的 Django 和字段集

Django 字符串到日期格式

如何在 django 模板中呈现有序字典?