[英]Render template located in a unregistered folder in Django
On my site i have demo
template in specific folder: 在我的网站上,我在特定文件夹中有
demo
模板:
project_root
├── project
│ ├── design # templates
│ │ ├── demo # template folder
│ │ │ └── index.html # template file
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── some_app
│ └── ...
└── manage.py
I have tried to use TemplateView
to render my demo/index.html
from specific url but Django fails to find my template, even if i add /project/design
to TEMPLATE_DIRS
or TEMPLATES
. 我试图使用
TemplateView
从特定的URL呈现我的demo/index.html
,但是Django无法找到我的模板,即使我将/project/design
添加到TEMPLATE_DIRS
或TEMPLATES
。
I need to render template using demo/index.html
string having templates in /project/design
folder. 我需要使用在
/project/design
文件夹中具有模板的demo/index.html
字符串来呈现模板。 How do i do that? 我怎么做?
Add in the right template engine that you use, for example DjangoTemplate , this directory. 在您使用的正确模板引擎中添加此目录,例如DjangoTemplate 。
Eg ( settings.py
file) : 例如(
settings.py
文件):
from unipath import Path
BASE_DIR = Path(__file__).ancestor(2)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/project/design/',
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Check that BASE_DIR
variable corresponds to the folder that contains all your apps. 检查
BASE_DIR
变量是否对应于包含所有应用程序的文件夹。
After that,rend your template with : 之后,使用以下代码租用您的模板:
return render(request, 'demo/index.html')
Best practice : Put your templates in project_root/templates/<app_name>/
or in templates/<app_name>
folder of each apps. 最佳实践 :将模板放在每个应用程序的
project_root/templates/<app_name>/
或templates/<app_name>
文件夹中。
Read this for more information about templates : Django - Templates 阅读有关模板的更多信息: Django-模板
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.