什么是Template:
- HTML文件
- 使用了某种模板语言
准备工作:配置 settings.py 中的 TEMPLATES
将 BACKED 替换为使用的模板,这里使用默认的 django 模板
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
步骤:
- 在APP目录中创建名叫 templates 的目录
- 在该目录下创建HTML文件
- 在 views.py 中返回 render()
目录结构:
render( )函数
它的作用就是将数据填充进模板文件,最后把结果返回给浏览器。
参数:
- request: 一个固定参数。
- template_name: templates 中定义的文件, 要注意路径名.
- context: 要传入文件中用于渲染呈现的数据, 默认是字典格式
- content_type: 生成的文档要使用的MIME 类型。默认为DEFAULT_CONTENT_TYPE 设置的值。
- status: http的响应代码,默认是200.
- using: 用于加载模板使用的模板引擎的名称。
views.py
from django.shortcuts import render
def index(request):
return render(request, 'index.html', {'hello': 'hello ,django'})
html页面
在html页面中使用{{键}}的形式获取字典中对应值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{hello}}</h1>
</body>
</html>
结果:
注意
Django会按照 settings.py 中 INSTALLED_APPS 中添加的顺序查找Template,也就是说:
如果一个项目中存在多个APP且模板名相同会默认显示第一个
解决办法:
在APP中 Template 目录下创建以APP名为名称的目录,将模板放到新建目录下
并在 runder() 函数的 context 参数中指明路径
下一篇:Django之Models https://blog.csdn.net/qq_36110736/article/details/84589752