Templates
加上 HTML / CSS & 动态内容
上一章的例子,只是很简单的显示一行字串。让我们加上一些 HTML/CSS 美化网页,并动态显示每次进来这个页面的时间:
# trips/views.py
from datetime import datetime
from django.http import HttpResponse
def hello_world(request):
output = """
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Hello World! <em style="color:LightSeaGreen;">{current_time}</em>
</body>
</html>
""".format(current_time=datetime.now())
return HttpResponse(output)
- 多行字串:
"""..."""
或是'''...'''
(三个双引号或三个单引号) 是字串的多行写法,这裡我们使用它表达 HTML,并维持原有的缩排。 - 显示目前时间:
为了显示动态内容,我们 import datetime 时间模组,并用
datetime.now()
取得现在的时间。 - 字串格式化:
使用 format() 格式化字串,将 datetime.now() 产生的值,代入
{current_time}
在字串中的位置。
现在启动 web server ,连至 http://127.0.0.1:8000/hello/ 后,会发现网页不再是纯文字。除了加上了一些样式外,也会显示当下的时间。
你可以重新整理网页,试试看时间有没有改变
第一个 Template
在前一个例子,我们把 HTML/CSS 放在 View function 裡。但在实务上,我们会将前端的程式码独立出来,放在 templates 资料夹裡。不仅增加可读性,也方便与设计师或前端工程师分工。
Template 资料夹
首先建立 Template 资料夹。开启终端机 (如果不想关闭 web server,可以再开新一个新的终端机视窗) ,并确认目前所在位置为 djangogirls/mysite/
。
新增一个名为 templates
的资料夹`:
(djangogirls_venv) ~/djangogirls/mysite$ mkdir templates
设定 Templates 资料夹的位置
建立好资料夹以后,我们需要修改 mysite/settings.py
中的 TEMPLATES
设定:
# mysite/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],
'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',
],
},
},
]
我们将 'DIRS'
原本的 []
修改成:
[os.path.join(BASE_DIR, 'templates').replace('\\', '/')]
好让 Django 找得到刚刚建立的 templates
资料夹。
建立第一个 Template
新增档案 templates/hello_world.html
,并将之前写在 view function 中的 HTML 复制到 hello_world.html
:
mysite
├── mysite
├── templates
│ └── hello_world.html
├── trips
└── manage.py
为了区别,我们做了一些样式上的调整:
<!-- hello_world.html -->
<!DOCTYPE html>
<html>
<head>
<title>I come from template!!</title>
<style>
body {
background-color: lightyellow;
}
em {
color: LightSeaGreen;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<em>{{ current_time }}</em>
</body>
</html>
在 Template 中显示变数
以上 template 中,有个地方要特别注意:
<em>{{ current_time }}</em>
仔细比较,可以发现变数 current_time
的使用方式与之前不同,在这裡用的是两个大括号。
{{
<variable_name>
}}
是在 Django Template 中显示变数的语法。
其它 Django Template 语法,我们会在后面的章节陆续练习到。
使用 render function
最后,将 view function hello_world
修改如下:
# trips/views.py
from datetime import datetime
from django.shortcuts import render
def hello_world(request):
return render(request, 'hello_world.html', {
'current_time': datetime.now(),
})
我们改成用 render
这个 function 产生要回传的 HttpResponse
物件。
这次传入的参数有:
- request --
HttpRequest
物件 - template_name -- 要使用的 template
- dictionary -- 包含要新增至 template 的变数
render
:产生 HttpResponse 物件。
render(request, template_name, dictionary)
大功告成
HTML 程式码独立成 template 后,程式也变得简洁许多了。
重新载入 http://127.0.0.1:8000/hello/ ,你会发现画面有了小小的改变:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论