TEMPLATE 默认配置
settings.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
TEMPLATES
=
[
{
'BACKEND'
:
'django.template.backends.django.DjangoTemplates'
,
'DIRS'
: [os.path.join(BASE_DIR,
'templates'
)],
'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'
,
],
},
},
]
|
BACKEND:模板引擎类的python路径,内置的模板引擎分别有'
django.template.backends.django.DjangoTemplates'和'
django.template.backends.jinja2.Jinja2
'
DIRS:模板引擎搜索模板的路径,如上,默认搜索project目录下的templates目录
APP_DIRS:告诉模板引擎是否搜索app目录下的templates目录。默认为true,即是默认搜索app目录下的templates目录
'DIRS': [os.path.join(BASE_DIR, 'templates')] 是指到 BASE_DIR/templates文件夹中去取模板
'DIRS': [os.path.join(BASE_DIR, 'app1/templates')] 是指到 BASE_DIR/app1/templates文件夹中去取模板
模板文件查找顺序
如果同时设置
'DIRS'
: [os.path.join(BASE_DIR,
'templates'
)],
'APP_DIRS'
:
True
,
并且同时存在
mysite\templates\polls\index.html
mysite\polls\templates\polls\index.html
则会访问 mysite\templates\polls\index.html 而不是 mysite\polls\templates\polls\index.html
模板文件命名空间
First, create a directory called templates
in your polls
directory. Django will look for templates in there.
Your project’s TEMPLATES
setting describes how Django will load and render templates. The default settings file configures aDjangoTemplates
backend whose APP_DIRS
option is set to True
. By convention DjangoTemplates
looks for a “templates” subdirectory in each of the INSTALLED_APPS
.
Within the templates
directory you have just created, create another directory called polls
, and within that create a file calledindex.html
. In other words, your template should be at polls/templates/polls/index.html
. Because of how theapp_directories
template loader works as described above, you can refer to this template within Django simply aspolls/index.html
.
Template namespacing
Now we might be able to get away withputting our templates directly in polls/templates
(rather than creating anotherpolls
subdirectory), but it would actually be a bad idea.Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.
xys友情提醒:
模板文件的命名空间(其实质是模板文件的本地相对路径)的应用场景是,在每个APP下建立appname/templates/appname/,然后在该目录下再放模板文件(index.html)。然后在需要引用模板文件的地方,采用模板文件相对地址硬编码时,形式如下:appname/index.html.
例如在views.py中
def index(request):
#return HttpResponse("Hello, world. You're at the polls index.")
return render(request,'polls/index.html')
或者index.html中
<li><ahref="/polls/xxx.html">{{question.question_text}}</a></li>
这根URL命名空间不一样:URL命名空间是用于模板文件中对URL(所谓URL是浏览器访问时的网络地址)的反向引用,一般会使用模板标签{% url %}
例如在index.html中
{% url 'polls:detail' question.id %}"