前言
前面介绍了django项目创建,今天在项目里面解析模板部分
一、模板作用
模板是一个文本,用于分离文档的表现形式和内容
二、渲染变量到模板
在项目目录下新建一个templates文件夹,作用是存放模板文件
新建一个index.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Content Page</title>
</head>
<body>
<p>{{hello}}</p>
{% comment %} <p>{{变量名}}</p> {% endcomment %}
</body>
</html>
修改模板文件的路径,修改project/settings.py,修改 TEMPLATES 中的 DIRS 为 [os.path.join(BASE_DIR, 'templates')]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, 'templates')], # 修改位置(这里需要在头部增加一行 import os,不然会报错)
'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',
],
},
},
]
在project项目下增加一个contents.py,写入内容
from django.shortcuts import render
def content(request):
# {"HTML变量名" : "views变量名"}
return render(request, 'index.html', {'hello' : 'Hello World!'})
在urls.py文件中增加信息:
访问http://127.0.0.1:8000/content
三、渲染列表/字典到模板
在index.py里面新增方法
def lists(request):
data = ["第一条数据","第二条数据","第三条数据"]
my_list = [
{'1': 'value1', '2': 'value2'},
{'k3': 'v3', 'ke4': 'val4'},
]
return render(request,"list.html", {"list":data, "my_list":my_list})
在templates新增list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Content Page</title>
</head>
<body>
<p>取出整个列表:</p>
<p>{{ list }}</p>
<p>取出列表的第一个元素</p>
<p>{{ list.0 }}</p>
<p>使用for循环取出list列表的每个元素:</p>
<ul>
{% for item in list %}
<li>值:{{item}}</li>
{% endfor %}
</ul>
<p>使用for循环取出my_list列表中每个字典的键值对:</p>
<ul>
{% for dict_item in my_list %}
<li>
<ul>
{% for key, value in dict_item.items %}
<li>{{ key }}: {{ value }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</body>
</html>
在urls.py引入from .index import lists
和path('lists', lists),
访问http://127.0.0.1:8000/lists