1)创建模版文件夹
2)配置模版目录
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',
],
},
},
]
3)使用模版文件
def my_render(request,templates_path,context_dict = {}):
# 1、加载模版文件
temp = loader.get_template(templates_path)
# 2、定义模版上下文,给模版文件传递数据
context = {} # RequestContext(request,{})
# 3、模版渲染,产生标准的html内容
res_htmp = temp.render(context)
# 4、返回浏览器
return HttpResponse(res_htmp)
给模版文件传递数据
模版变量的使用
{{ 模版变量名 }}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模版文件</title>
</head>
<body>
<h1>这是一个模版文件</h1>
使用模版变量:<br/>
{{ content }}<br/>
使用列表:<br/>
{{ list }}<br/>
for 循环 : <br/>
<ul>
{% for i in list %}
<li>{{ i }}</li>
{% endfor %}
</ul>
</body>
</html>
视图函数
from django.shortcuts import render
def index(request):
# 进行处理 和M和T进行交互
# return HttpResponse("老铁,没毛病")
# 使用模版文件
# return my_render(request,'booktest/index.html')
return render(request,'booktest/index.html',
{'content':'hello','list':list(range(1,10))})







网友评论