一、views.py 的代码

class Person(object): def __init__(self,name,age): self.name = name self.age = agedef 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> <h2>Django模板变量使用</h2> <h3>变量</h3> <div>{{ name }}</div> <h3>列表</h3> <div> {{ name_list }} </div> <ul> {% for name in name_list %} <li>{{ name }}</li> {% endfor %} </ul> <h3>通过index获取值</h3> <div>{{ name_list.0 }} {{ name_list.1 }} {{ name_list.2 }}</div> <h3>字典</h3> <div>{{ name_dict.first_name }} {{ name_dict.last_name }}</div> <h3>类实例化</h3> <div>{{ person }}</div> <div>{{ person.name }} {{ person.age }}</div></body></html>三、展示效果

四、Filter的使用

语法: {{ value|filter_name:参数}}设置默认值:{{ bucunzia|default:”这个变量不存在”}} 统计字长节长度{{ name|length}}统计文件大小{{ value|filesizeformat}}切片{{ name_list|slice:”1:-1” }}时间格式化{{ value|date:”Y-m-d H:i:s”}}…摘要信息{{ p_str|truncatechars:20 }}