Django模板之模板标签
标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息到模版中。
一些标签需要开始和结束标签 (例如:{% tag %} ...标签 内容 ... {% endtag %}),有些标签不需要结束{% tag %}
快捷键:输入tag直接回车
常用模板标签:for if with [csrf_token extends include block url load]见后续页面
for标签:循环遍历可迭代变量中的每一个元素,没有break和continue等复杂功能,相关操作类比python。
(1)遍历列表:
tagtest.html模板:
{% for name in name_list %}
<li>{{ name }}</li>
{% endfor %}
反向遍历:
{% for name in name_list reversed %}
<li>{{ name }}</li>
{% endfor %}
views.py视图:
def tagtest(request):
list=["zhang","wang","li"]
return render(request,"tagtest.html",{"name_list":list})
渲染结果:
(2)列表中字典取值:
tagtest.html模板:
{% for info_dic in name_list %}
<li>{{ info_dic.name }}</li>
{% endfor %}
views.py视图:
def tagtest(request):
list=[{"name":"le"},{"name":"yang"},{"name":"he"}]
return render(request,"tagtest.html",{"name_list":list})
渲染结果:
(3)遍历字典:
tagtest.html模板:
{% for k,v in info_dict.items %}
<li>{{ k }}:{{ v }}</li>
{% endfor %}
views.py视图:
def tagtest(request):
dic={"name":"yang","age":20,"sex":"male"}
return render(request,"tagtest.html",{"info_dict":dic})
渲染结果:
(4)for…empty…:for遍历一个空的变量或者未找到时执行empty
tagtest.html模板:
{% for info_dic in name_list %}
<li>{{ info_dic.name }}</li>
{% empty %}
<p>给出的变量为空或者未找到!</p>
{% endfor %}
views.py视图:
def tagtest(request):
list=[]
return render(request,"tagtest.html",{"name_list":list})
渲染结果:
(5)forloop使用案例:
tagtest.html模板:
{% for i in l %}
<li>{{ forloop }}---{{ i }}</li>
{% endfor %}
配合属性使用:
{% for i in l %}
<li>{{ forloop.counter }}---{{ i }}</li>
{% endfor %}
views.py视图:
def tagtest(request):
li=["python","mysql","web"]
return render(request,"tagtest.html",{"l":li})
渲染结果:
注:循环序号可以通过{{forloop}}显示,必须在循环内部用:
forloop.counter |
当前循环的索引值(从1开始),forloop是循环器,通过点来使用功能 |
forloop.counter0 |
当前循环的索引值(从0开始) |
forloop.revcounter |
当前循环的倒序索引值(从1开始) |
forloop.revcounter0 |
当前循环的倒序索引值(从0开始) |
forloop.first |
当前循环是不是第一次循环(布尔值) |
forloop.last |
当前循环是不是最后一次循环(布尔值) |
forloop.parentloop |
本层循环的外层循环的对象,再通过上面的几个属性来显示外层循环的计数等 |
if标签:判断变量的逻辑值是进行选择性的输出,类比python(< > = <= >= != == and or not not in is is not前后必须要有空格)
tagtest.html模板:
{% if num > 100 %}
<h1>大于100</h1>
{% elif num < 100 %}
<h1>小于100</h1>
{% else %}
<h1>等于100</h1>
{% endif %}
views.py视图:
def tagtest(request):
n=100
return render(request,"tagtest.html",{"num":n})
渲染结果:
with标签:多用于给一个复杂的变量起别名
注意:等号左右不要加空格。
{% with total=business.employees.count %}
{{ total }} <!--只能在with语句体内用-->
{% endwith %}
或
{% with business.employees.count as total %}
{{ total }}
{% endwith %}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具