一:模板变量
通过视图函数中向模板可以传递数据,传递到模板中的数据可以通过 模板变量的方式显示出来,通过模板语法{{ 模板变量名 }}。 传递给模板的数据,包括字符串、数字等简单数据类型,还可以包括 字典、对象、列表。
可以通过模板中的“点语法”获取复杂对象的相关值。例如:字典中的某个key对应的值,对象的属性、对象的方法(除了self外,无参),列表的某一项(不能访问负数索引)。
二:模板标签——控制标签
1. if标签
{% if 布尔值 %} 布尔值为True时,显示的内容 {% else %} 布尔值为False时,显示的内容 {% endif %} 注意:可以在if后添加and、or、not,逻辑判断符号。 判断是否相等,使用"=="符号。
补充:可以有多分支判断: {% if score >= 90 %} 优秀 {% elif score >= 80 %} 良好 {% elif score >= 60 %} 一般 {% else %} 不及格 {% endif %}
2. for标签
{% for 循环变量 in 循环序列 %} {{ 循环变量 }} {% empty %} 如果循环序列为空,执行此处{% endfor %}
注意:使用for标签循环时,有一个forloop模板变量,用来记录当前循环进度的。 forloop的常用属性:counter、first、last。 如果要进行反向循环,则在for标签的循环序列后加上reversed。
三:模板包含与继承
1. 模板包含
{% include '包含的模板地址' %}
2. 模板继承
父模板(基模板)提前定义若干个block块标签,子模板可以继承、重写、添加父模板block块中的内容。子模板通过{% extends '父模板位置' %}继承父模板。父模板使用{% block 块名称 %} {% endblock %}进行“挖坑”,子模板“填坑”。子模板如果想要在父模板的某个块中添加内容,则先要使用{{ block.super }}获取父模板中该块的内容。
四:模板过滤器
模板过滤器的作用是将要输出的变量进行过滤后显示,变量后面添加管道符,管道 符后是过滤器名称,有的过滤器需要传递参数。 常用过滤器: length 获取模板变量对应值的长度 first 获取第一个元素 upper 变为大写 lower 变为小写 truncatewords 截取指定数量的字符,该过滤器需要参数 date 显示日期,该过滤器需要参数,eg: date:"Y-m-d H:i:s" addslashes 在单引号、双引号、反斜线前添加斜线 add 在模板变量上添加指定的数据
五、附录
1、Django项目源代码
#主路由 (Djangoday2/urls.py) from django.contrib import admin from django.urls import path,include urlpatterns = { path('admin/', admin.site.urls), path('myapp/', include('myapp.urls')), path('stuapp/',include('studentapp.urls')),
1.1 myapp
#子路由配置 (Djangoday2/myapp/urls.py) from django.urls import path,include from myapp.views import * urlpatterns = [ path('dict/',pass_dict), path('student/',pass_student), path('fruits/',pass_list), path('ifdemo/',athletes_coaches), path('fordemo/',show_books), path('gomain/',go_main), path('gochild/',go_child), path('filter/',filter_demo) ]
#视图函数(Djangoday2/myapp/view.py) from django.shortcuts import render from myapp.student import Student from datetime import datetime # Create your views here. def pass_dict(request): product = {'name':'洗衣机','price':12.5,'brand':'中国洗衣机'} return render(request,'mytemplates/product.html',{'product':product}) def pass_student(request): stu = Student("东方不败",25,'女',99.5) return render(request,'mytemplates/student.html',{'student':stu}) def pass_list(request): fruits = ["苹果","香蕉","j橘子"] return render(request,'mytemplates/fruits.html',{'fruits':fruits}) def athletes_coaches(request): athletes = ["刘翔","乔丹"] # coaches = ["张三","李四"] coaches =[] chearleaders = ["小红","小丽"] a,b = 100,50 return render(request,'templatetags/ifdemo.html',locals()) def show_books(request): books = ["三国演义","西游记","水浒传","红楼梦"] games = [] return render(request,'templatetags/fordemo.html',locals()) def go_main(request): return render(request,'templateinclude/main.html') def go_child(request): return render(request,'extends/child.html') def filter_demo(request): sports = ["basktball","pingpang","football"] sentenes = "you are a fulish man and you have to improve yourself..." t = datetime.now() say = "he said:'you epress you as fluently as you can'" name = 100 return render(request,'filter/filterdemo.html', locals())
2、显示模板
<! product.html 字典传递访问 Djangoday2/myapp/mytemplates/product.html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板接受字典</title> </head> <body> <h3>产品名称:{{product.name }}</h3> <h3>产品价格:{{product.price}}</h3> <h3>产品品牌:{{product.brand }}</h3> </body> </html>
<!学生类传递访问模板 Djangoday2/myapp/mytemplates/student.html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板接收对象</title> </head> <body> <h3>学生姓名:{{ student.name }}</h3> <h3>学生性别:{{ student.sex }}</h3> <h3>学生年龄:{{ student.age }}</h3> <h3>学生成绩:{{ student.score }}</h3> <h3>调用方法:{{ student.learn }}</h3> </body> </html>
#student类定义 class Student: def __init__(self,name,age,sex,score): self.name = name self.age = age self.sex = sex self.score = score def learn(self): return "我叫"+self.name+"正在学习..."
<!列表传递访问模板 Djangoday2/myapp/mytemplates/fruits.html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板接受列表</title> </head> <body> <h3>列表中的第一项:{{ fruits.0 }}</h3> <h3>列表中的第二项:{{ fruits.1 }}</h3> <h3>列表中的第三项:{{ fruits.2 }}</h3> </body> </html>
if标签 myapp/templates/templatetags/ifdemo,html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>条件判断</title> </head> <body> {% if athletes and coaches %} <h3>ther are some athletes and coaches</h3> {% else %} <h3>没有运动员和教练</h3> {% endif %} {% if not coaches %} <h3>没有教练</h3> {% endif %} {% if athletes or coaches %} <h3>有运动员或者教练</h3> {% endif %} {% if athletes and coaches or chearleaders %} <h3>there are athletes and coaches or chearleaders</h3> {% endif %} {% if a == b %} <h3>a与b相等</h3> {% else %} <h3>a与b不相等</h3> {% endif %} </body> </html>
for 标签 myapp/templates/templatetags/ifdemo,html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>书籍信息</title> <style> .first{ color: red; } </style> </head> <body> <ul> {% for book in books %} {# books后+reversed倒序#} {% if forloop.first%}<li class="first">{% else %}<li>{% endif %} {{ book }} </li> {% endfor %} </ul> {% for book in books %} {{ book }} {% if not forloop.last %}|{% endif %} {% endfor %} <br/> {% for game in gemes %} {{ game }} {% empty %} 怎么没有游戏 {% endfor %} </body> </html>
包含标签 myapp/templates/templateinclude/nav.html 首页 娱乐 电影 新闻 其他 包含标签 myapp/templates/templateinclude/footer.html 联系电话:158xxxxx 友情链接:百度 搜狐 腾讯 包含标签 myapp/templates/templateinclude/main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>主页面</title> </head> <body> {% include 'templateinclude/nav.html' %} <h3>welcome to our web site...</h3> {% include 'templateinclude/footer.html' %} </body> </html>
继承标签. 父模板myapp/templates/extend/base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> <h3>欢迎光临</h3> <br/> {% block content %} 中一些书。。。<br/> 开公司。。。。<br/> {% endblock %} <br/> {% block footer %} <div> 联系地址:西安市 <br/> 联系电话:15824525<br/> 联系单位:市委办公室<br/> </div> {% endblock %} </body> </html> 子模版 myapp/templates/extend/base.html {% extends 'extends/base.html' %} {% block title %} 新任书记{% endblock %} {% block content %} {{ block.super }} #继承 反腐败。。。。<br/> {% endblock %}
模板过滤器 myapp/templates/filter/filter.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>演示过滤器</title> </head> <body> <h3>列表长度;{{ sports|length }}</h3> <h3>第一个大写:{{ sports|first|upper }}</h3> <h3>获取5个单词:{{ sentenes|truncatewords:"5" }}</h3> <h3>现在时间:(无过滤器){{ t }}</h3> <h3>现在时间(有date过滤器){{ t|date:"Y-m-d H:i:s" }}</h3> <h3>addslashes过滤器:{{ say| addslashes }}</h3> <h3>add过滤器:{{ name|add:"5" }}</h3> </body> </html>
1.2studentapp
#子路由配置 from django.urls import path from studentapp.views import * urlpatterns = [ path('students/',show_student), path('student/<int:stuid>/',select_student), ]
#视图函数 from django.shortcuts import render from studentapp.student import Student students =[] def show_student(requert): stu1 =Student(1,"风清扬",25,69.5) stu2 = Student(2, "张三", 15, 90) stu3 = Student(3, "令狐冲", 35, 84) stu4 = Student(4, "小丽", 29, 89.5) stu5 = Student(5, "东方不败", 23, 58.5) # students = [] students.append(stu1) students.append(stu2) students.append(stu3) students.append(stu4) students.append(stu5) return render(requert,'students.html',{"students":students}) def select_student(request,stuid): for student in students: if student.stuid == stuid: return render(request,'student_detail.html',{"student":student})
#student类定义 class Student: def __init__(self,stuid, name,age, score): self.stuid = stuid self.name = name self.age = age self.score = score
<!显示模板> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>学生信息</title> </head> <body> <table border="1" align="center"> <thead> <tr> <th>学号</th> <th>姓名</th> <th>年龄</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.stuid }}</td> <td><a href="/stuapp/student/{{ student.stuid }}"> {{ student.name }}</a></td> <td>{{ student.age }}</td> </tr> {% endfor %} </tbody> </table> </body> </html>
<!显示详细信息,超链接后模板> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ student.name }}</title> </head> <body> <h3>学号:{{ student.stuid }}</h3> <h3>姓名:{{ student.name }}</h3> <h3>年龄:{{ student.age }}</h3> <h3>成绩:{{ student.score }}</h3> </body> </html>
2、浏览器访问结果
2.1 myapp
http://localhost:8000/myapp/fordemo/ #for标签结果 访问
- 三国演义
- 西游记
- 水浒传
- 红楼梦
三国演义 | 西游记 | 水浒传 | 红楼梦
怎么没有游戏
http://localhost:8000/myapp/ifdemo/ #if标签结果访问
没有运动员和教练
没有教练
有运动员或者教练
there are athletes and coaches or chearleaders
a与b不相等
http://localhost:8000/myapp/gomain/ #包含标签访问
首页 娱乐 电影 新闻 其他
welcome to our web site...
联系电话:158xxxxx 友情链接:百度 搜狐 腾讯
http://localhost:8000/myapp/gochild/ #继承模板访问
欢迎光临
中一些书。。。
开公司。。。。
反腐败。。。。
联系地址:西安市
联系电话:15824525
联系单位:市委办公室
http://localhost:8000/myapp/filter/ #模板过滤器
列表长度;3
第一个大写:BASKTBALL
获取5个单词:you are a fulish man ...
现在时间:(无过滤器)Oct. 5, 2018, 4:12 p.m.
现在时间:(有date过滤器)2018-10-05 16:12:32
slashes过滤器:he said:\'you epress you as fluently as you can\'
addslashes过滤器:105
2.2 studentapp
http://localhost:8000/stuapp/students/ #学生信息查询
学号 姓名 年龄
1 风清扬 25
2 张三 15
3 令狐冲 35
4 小丽 29
5 东方不败 23
# 姓名超链接:
http://localhost:8000/stuapp/student/1/ #自动生成
学号:1
姓名:风清扬
年龄:25
成绩:69.5