一、views.py 的代码
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def test(request):
‘‘‘
模板语言学习
:param request:
:return:
‘‘‘
name = "kang" #变量
name_list = ["Mingkang", "BearBear", "BenBen"] #列表
name_dict = {"last_name":"Kang","first_name":"Mingkang"} #字典
person1 = Person("kang",18) #类
return render(request,
"test.html",
{"name":name,
"name_list":name_list,
"name_dict":name_dict,
"person":person1}
)
二、html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Django模板变量使用</h1>
<h2>变量</h2>
<div>{{ name }}</div>
<h2>列表</h2>
<div>
{{ name_list }}
</div>
<ul>
{% for name in name_list %}
<li>{{ name }}</li>
{% endfor %}
</ul>
<h2>通过index获取值</h2>
<div>{{ name_list.0 }} {{ name_list.1 }} {{ name_list.2 }}</div>
<h2>字典</h2>
<div>{{ name_dict.first_name }} {{ name_dict.last_name }}</div>
<h2>类实例化</h2>
<div>{{ person }}</div>
<div>{{ person.name }} {{ person.age }}</div>
</body>
</html>
三、展示效果
原文地址:https://blog.51cto.com/12965094/2383342
时间: 2024-11-09 20:19:44