Django 5.2 默认提供了丰富的内置模板标签,用于控制模板逻辑和渲染。以下是主要标签及其用法详解:
条件判断标签
{% if %}/{% elif %}/{% else %}
用于条件判断,支持逻辑运算符(如 ==、!=、in 等)。
{% if user.is_authenticated %}
<p>欢迎, {{ user.username }}!</p>
{% else %}
<p>请登录。</p>
{% endif %}循环标签
{% for %}
遍历列表、字典等可迭代对象,支持反向遍历(reversed)和嵌套循环。
遍历
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>反向遍历
反向遍历示例(使用reversed参数)
假设有个列表[1,2,3],正常遍历是1→2→3,反向则是3→2→1
{% for year in years reversed %}
<h2>{{ year }}</h2>
{% for month in months %}
<p>{{ month }}月</p>
{% endfor %}
{% endfor %}传入{'items': ['苹果', '香蕉', '橙子']}会显示:3:橙子 2:香蕉 1:苹果
嵌套循环
可以循环套循环处理二维数据
{% for category in categories %}
<h3>{{ category.name }}</h3>
<ul>
{% for product in category.products %}
<li>{{ product.name }} - ¥{{ product.price }}</li>
{% endfor %}
</ul>
{% endfor %}传入数据需包含categories列表,每个category对象有products属性
组合使用
反向遍历外层,正常遍历内层
{% for year in years reversed %}
<h2>{{ year }}</h2>
{% for month in months %}
<p>{{ month }}月</p>
{% endfor %}
{% endfor %}注意事项:
- reversed只能用于可迭代对象,不能用于QuerySet的order_by反向
- 嵌套循环时可以使用{{ forloop.parentloop }}访问外层循环变量
- 复杂嵌套建议在view中预处理数据,减少模板逻辑
特殊变量:
forloop.counter(从1开始)
forloop.counter0(从0开始)
forloop.revcounter(反向计数)
forloop.first/forloop.last(首/末项判断)
我们来详细举例说明Django模板中for循环的这些特殊变量用法:
forloop.counter(从1开始计数):
<ul>
{% for item in ['a','b','c'] %}
<li>第{{ forloop.counter }}个字母是:{{ item }}</li>
{% endfor %}
</ul> 输出: 1. 第1个字母是:a 2. 第2个字母是:b 3. 第3个字母是:c
forloop.counter0(从0开始计数):
<table>
{% for user in users %}
<tr class="{% cycle 'row1' 'row2' %}">
<td>索引{{ forloop.counter0 }}</td>
<td>{{ user.name }}</td>
</tr>
{% endfor %}
</table> 输出: 索引0 | 张三 索引1 | 李四 索引2 | 王五
forloop.revcounter(反向计数):
{% for num in nums reversed %}
剩余{{ forloop.revcounter }}项: {{ num }}
{% endfor %}
假设nums=[10,20,30],输出:
剩余3项: 30
剩余2项: 20
剩余1项: 10
forloop.first/last(首末项判断):
{% for product in products %}
{% if forloop.first %}
<strong>首项:</strong>
{% endif %}
{{ product.name }}
{% if forloop.last %}
<em>(最后一项)</em>
{% else %}
,
{% endif %}
{% endfor %}
输出示例:
首项:手机, 电脑, 平板(最后一项)
组合使用示例:
{% for item in items %}
{% if forloop.first %}
<ul>
{% endif %}
<li class="{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}">
{{ forloop.counter }}/{{ forloop.revcounter }}: {{ item }}
</li>
{% if forloop.last %}
</ul>
{% endif %}
{% endfor %}
这些变量在分页显示、交替行样式、特殊标记首尾项等场景非常实用。
模板继承标签
{% extends %}
继承父模板,需放在模板开头。
{% extends "base.html" %}
{% block %}
定义可被子模板覆盖的内容块。
{% block content %}
<h1>子模板内容</h1>
{% endblock %}
URL 路由标签
{% url %}
根据路由名称生成 URL,避免硬编码。
<a href="{% url 'user_profile' user.id %}">个人资料</a>
安全防护标签
{% csrf_token %}
生成 CSRF 令牌,用于表单提交防护。
<form method="post">
{% csrf_token %}
<input type="submit" value="提交">
</form>
变量重命名标签
{% with %}
临时重命名复杂变量,简化代码。
{% with total=products|length %}
<p>商品总数: {{ total }}</p>
{% endwith %}
注释标签
{% comment %}
注释内容不会被渲染。
{% comment "临时注释" %}
<p>这段代码暂不生效</p>
{% endcomment %}
静态文件标签
{% static %}
加载静态文件(需配合 {% load static %})。
{% load static %}
<img src="{% static 'images/logo.png' %}">
自动转义控制标签
{% autoescape %}
控制 HTML 自动转义(on/off)。
{% autoescape off %}
{{ user_input }} <!-- 原样输出未转义内容 -->
{% endautoescape %}循环辅助标签
{% empty %}
与 {% for %} 配合,当遍历对象为空时显示内容。
{% for item in items %}
<p>{{ item }}</p>
{% empty %}
<p>暂无数据</p>
{% endfor %}
原生内容标签
{% verbatim %}
禁止模板引擎解析内容,常用于嵌入前端框架(如 Vue.js)。
{% verbatim %}
{{ vue_variable }} <!-- 不会被 Django 解析 -->
{% endverbatim %}加载自定义标签库
{% load %}
加载自定义标签或过滤器库。
{% load custom_tags %}以上是 Django 5.2 的核心内置模板标签,覆盖了逻辑控制、数据渲染、安全防护等常见场景。如需更复杂功能(如自定义标签),可参考官方文档扩展。
过滤标签》》
以下是 Django 5.2 的全部内置模板过滤器(按功能分类),包含用法示例和核心特性说明:
字符串处理
lower
转换为小写:{{ "HELLO"|lower }}→"hello"
upper
转换为大写:{{ "hello"|upper }}→"HELLO"
capfirst
首字母大写:{{ "django"|capfirst }}→"Django"
cut
移除指定字符:{{ "Hello World"|cut:" " }}→"HelloWorld"
truncatechars
截断字符(含省略号):{{ "Django is awesome"|truncatechars:10 }}→"Django ..."
truncatewords
截断单词:{{ "Django makes web easy"|truncatewords:2 }}→"Django makes ..."
数字与计算
add
加法运算(支持数字/列表合并):{{ 5|add:"3" }}→8{{ list1|add:list2 }}→ 合并列表
divisibleby
判断是否可整除:{{ 9|divisibleby:"3" }}→True
filesizeformat
文件大小格式化:{{ 1024|filesizeformat }}→"1 KB"
日期时间
date
日期格式化:{{ pub_date|date:"Y-m-d" }}→"2025-06-07"
time
时间格式化:{{ pub_date|time:"H:i" }}→"14:30"
列表/字典操作
join
列表连接为字符串:{{ list|join:", " }}→"a, b, c"
first/last
获取首/末元素:{{ list|first }}→ 第一个元素
length
获取长度:{{ list|length }}→3
dictsort
字典排序:{% for item in data|dictsort:"age" %}
默认值与空值处理
default
默认值替换:{{ value|default:"N/A" }}
default_if_none
仅当值为None时替换:{{ value|default_if_none:"空" }}
安全与转义
escape
HTML 转义:{{ "<script>"|escape }}→<script>
safe
标记内容为安全(不转义):{{ html_content|safe }}
force_escape
强制转义(即使已标记safe):{{ user_input|force_escape }}
其他实用过滤器
linebreaks
换行符转<br>/<p>:{{ "Hi\nDjango"|linebreaks }}→<p>Hi<br>Django</p>
urlencode
URL 编码:{{ "q=django"|urlencode }}→"q%3Ddjango"
pluralize
复数化:{{ count|pluralize:"y,ies" }}→"1 reply"/"2 replies"
以上过滤器均支持链式调用(如 {{ text|truncatewords:5|upper }})。完整列表可参考 Django 官方文档。