Django模版语法
(1)传数据
- 模版语法可以传递的后端python数据类型(可迭代)
- 后端:
| def test2(request): |
| name = 'heart' |
| float = 11.11 |
| str_name = '你好' |
| boolean_test = True |
| list_test = [1, 2, 3] |
| tuple_test = (1, 2, 3) |
| dict_test = {'name': 'heart', 'age': 18} |
| set_test = {1, 2, 3, 4, 5, 5} |
| return render(request,'mubanyufa.html', locals()) |
| <body> |
| {{ name }} |
| <br> |
| {{ float }} |
| <br> |
| {{ str_name }} |
| <br> |
| {{ boolean_test }} |
| <br> |
| {{ list_test }} |
| <br> |
| {{ tuple_test }} |
| <br> |
| {{ dict_test }} |
| <br> |
| {{ set_test }} |
| <br> |
| </body> |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
(2)传函数
| def test2(request): |
| name = 'heart' |
| |
| def func(): |
| return '这是一个函数' |
| return render(request,'mubanyufa.html', locals()) |
(3)传类
| def test2(request): |
| class MyClass(object): |
| def get_self(self): |
| return 'self' |
| |
| @staticmethod |
| def get_func(): |
| return 'func' |
| |
| @classmethod |
| def get_class(cls): |
| return 'cls' |
| |
| obj = MyClass() |
| return render(request,'mubanyufa.html', locals()) |
| <body> |
| {{ MyClass }} |
| {{ obj }} |
| {{ obj.get_class }} |
| {{ obj.get_func }} |
| {{ obj.get_self }} |
| </body> |
(4)小结
(5)过滤器
| {{数据|过滤器:参数}} |
| {{ value|filter_name:参数 }} |
- date: 格式化日期。例如:
{{ my_date|date:"Y-m-d" }}
- length: 获取列表或字符串的长度。例如:
{{ my_list|length }}
- filesizeformat: 获取文件大小。例如:
{{ my_file|filesizeformat}}
- default: 设置默认值。例如:
{{ my_var|default:"No value" }}
- lower: 将字符串转换为小写。例如:
{{ my_string|lower }}
- upper: 将字符串转换为大写。例如:
{{ my_string|upper }}
- truncatechars: 截断字符串到指定长度。例如:
{{ my_string|truncatechars:9 }}
- truncatewords: 截断单词到指定长度。例如:
{{ my_string|truncatewords:9 }}
- safe: 转义。例如:
{{ my_string|safe }}
- join: 拼接。例如:
{{ my_string|join:'123' }}
- slice: 切片。例如:
{{ my_string|slice:'0:4:2' }}
- cut: 移除指定字符。例如:
{{ value|cut:'1' }}
(6)标签
(1)for循环
| <ul> |
| {% for user in user_list %} |
| <li>{{ user.name }}</li> |
| {% endfor %} |
| </ul> |
(2)for循环可用的一些参数
Variable |
Description |
forloop.counter |
当前循环的索引值(从1开始) |
forloop.counter0 |
当前循环的索引值(从0开始) |
forloop.revcounter |
当前循环的倒序索引值(从1开始) |
forloop.revcounter0 |
当前循环的倒序索引值(从0开始) |
forloop.first |
当前循环是不是第一次循环(布尔值) |
forloop.last |
当前循环是不是最后一次循环(布尔值) |
forloop.parentloop |
本层循环的外层循环 |
(3)if判断
(1)if elif else
| {% if user_list %} |
| 用户人数:{{ user_list|length }} |
| {% elif black_list %} |
| 黑名单数:{{ black_list|length }} |
| {% else %} |
| 没有用户 |
| {% endif %} |
(2)if和else
| {% if user_list|length > 5 %} |
| 你好 |
| {% else %} |
| 世界 |
| {% endif %} |
(4)with
- 定义一个中间变量,多用于给一个复杂的变量起别名。
- 注意等号左右不要加空格。
| {% with total=business.employees.count %} |
| {{ total }} employee{{ total|pluralize }} |
| {% endwith %} |
| {% with business.employees.count as total %} |
| {{ total }} employee{{ total|pluralize }} |
| {% endwith %} |
(5)csrf_token
- 这个标签用于跨站请求伪造保护。
- 在页面的form表单里面写上
(6)forloop
| list = ["你好", "我好", "大家好"] |
| {% for re in list %} |
| |
| <p>{{ forloop }}</p> |
| |
| {% endfor %} |
| 标签 |
| {'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 3, 'revcounter0': 2, 'first': True, 'last': False} |
| |
| {'parentloop': {}, 'counter0': 1, 'counter': 2, 'revcounter': 2, 'revcounter0': 1, 'first': False, 'last': False} |
| |
| {'parentloop': {}, 'counter0': 2, 'counter': 3, 'revcounter': 1, 'revcounter0': 0, 'first': False, 'last': True} |
- first
- last
- counter0
- counter
- 取值
(1)if+forloop
| {% for re in d %} |
| {% if forloop.first %} |
| <p>第一次循环</p> |
| {% elif forloop.last %} |
| <p>最后一次循环</p> |
| {% else %} |
| <p>{{ re }}</p> |
| {% endif %} |
| {% empty %} |
| <p>for循环的对象是空,不支持for循环</p> |
| |
| {% endfor %} |
(7)自定义过滤器、标签、inclusion_tag
(1)自定义过滤器
- 在应用下创建一个名字必须叫templatetags文件夹
- 在该文件夹内创建任意名字的py文件 eg:mytag.py
- 在该py文件内必须书写下面两句话
| from django import template |
| |
| register = template.Library() |
| from django import template |
| |
| register = template.Library() |
| |
| |
| @register.filter(name='heart') |
| def mysum(v1, v2): |
| return v1 + v2 |
| def test2(request): |
| float = 11.11 |
| return render(request,'mubanyufa.html', locals()) |
| {% load mytag %} |
| <p>{{ float|heart:666 }}</p> |
(2)自定义标签
| from django import template |
| |
| register = template.Library() |
| |
| |
| @register.simple_tag(name='plus') |
| def index(a,b,c,d): |
| return '%s-%s-%s-%s'% (a,b,c,d) |
| <p>{% plus 'heart' 123 123 456 %}</p> |
(3)自定义inclusion_tag
-
先定义一个方法,在页面上调用该方法,并且可以传值,该方法会生成一些数据然后传递给一个html页面,之后将渲染好的结果放到调用的位置
-
当html页面某一个地方的页面需要传参数才能够动态的渲染出来,并且在多个页面上都需要使用到该局部,那么就考虑将该局部页面做成inclusion_tag形式
-
在templatetags下面的py文件:
| from django import template |
| |
| register = template.Library() |
| |
| @register.inclusion_tag('left_menu.html') |
| def left(n): |
| data = [f'第{i}项' for i in range(n)] |
| return locals() |
| <ul> |
| {% for foo in data %} |
| <li>{{ foo }}</li> |
| {% endfor %} |
| </ul> |

(8)模版继承
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta http-equiv="x-ua-compatible" content="IE=edge"> |
| <meta name="viewport" content="width=device-width, initial-scale=1"> |
| <title>Title</title> |
| {% block page-css %} |
| |
| {% endblock %} |
| </head> |
| <body> |
| {% block content %} |
| 模板内容 |
| {% endblock %} |
| </body> |
| </html> |
(1)继承模版
| {% extends 'home.html' %} |
- 修改模板就在子页面中定义母版的block名来对应替换相应的内容
| {% block content %} |
| <p>123</p> |
| <p>456</p> |
| <p>789</p> |
| {% endblock %} |
(2)模板的导入
| {% include 'test.html' %} |
(9)静态模版加载
(1)
| {% load static %} |
| <img src="{% static "images/hi.jpg" %}" alt="Hi!" /> |
| {% load static %} |
| <script src="{% static "mytest.js" %}"></script> |
| {% load static %} |
| {% static "images/hi.jpg" as myphoto %} |
| <img src="{{ myphoto }}"></img> |
(10)导出项目模块版本
| pip freeze > requirement.txt |
| pip install -r requirement.txt |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步