我尝试在我的 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/