上一节视图
使用django.http.HttpResponse()
来向页面返回内容,但是这样不符合 Django 的 MVT 思想,所以这一节将来记录 Django 模板的应用。
模板是一个文本,用于分离文档的表现形式和内容。
1、在项目根目录下,创建templates
目录,在templates
下新建index.html
文件,PyCharm将自动生成html的文件内容格式。
.
├── Book
├── BookManager
└── templates
└── index.html
2、编辑setting.py
文件第58行,修改TEMPLATES
内容如下,目的是添加templates
路径,好让接下来程序能够找到index.html
文件。
'DIRS': [os.path.join(BASE_DIR,'templates')],
3、修改view.py
文件如下。
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context={
'H1':'OK!',
'H2':'-- By TeamsSix'
}
return render(request,'index.html',context)
4、修改index.html
文件如下。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<H1 style="color:red;">{{ H1 }}</H1>
<H2 style="color:limegreen;">{{ H2 }}</H2>
</body>
</html>
5、此时,刷新浏览器。
6、视图与templates
的总结
原文链接:https://www.teamssix.com/year/200301-182831.html 参考链接: https://youtu.be/BXyGr9JQVcc https://www.runoob.com/django/django-template.html
往期推荐