一、模板渲染
render(request, template_name, context=None, content_type=None, status=None, using=None) 返回一个HttpResponse对象
from django.urls import path, re_path, include
from mysite import views
urlpatterns = [
path("index/", views.my_index)
]
from django.shortcuts import render
def my_index(request):
num = 100 # 传递数值
username = "Zhang Shan" # 传递字符串
ls = ["aa", "bb", "cc"] # 传递列表
d = {"k1":"v1", "k2":"v2", "x3":{"aa":111, "bb":222}} # 传递字典
class Person: # 传递对象
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def run(self):
return "running{}".format(self.name)
p1 = Person("li shi", 20, "male")
import datetime
time = datetime.datetime.now() # 传递时间
tag = "<a href='http//www.baidu.com'>百度首页</a>" # 传递标签
ct = {
"num":num,
"username":username,
"ls":ls,
"d":d,
"person":p1,
"time":time,
"tag":tag
}
# context=locals(),会把全部本地变量的值传递到前端页面
return render(request, "index.html", context=ct)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是index</title>
</head>
<body>
数值:{{ num }}
<br>
字符串:{{ username }}
<br>
列表:{{ ls }}
<br>
获取列表的某个元素:{{ ls.1 }}
<br>
字典:{{ d }}
<br>
根据字典的键获取值:{{ d.k1 }} <!-- 不能写成d."k1"-->
<br>
字典嵌套取值:{{ d.x3 }}
<br>
字典嵌套取里面的值:{{ d.x3.aa }}
<br>
获取对象类型:{{ person.name }}
<br>
获取时间:{{ time }}
<br>
tag:{{ tag|safe }}
</body>
</html>
source, django, bilibili