介绍下html的一些语法
1.for循环
<body>
{% for song in songs %}
<hr>
<h1>{{ song.name }}</h1>
{% endfor %}
</body>
2.字典中索引取值
<h3>{{ songs.0.name}}</h3>
3.占位(只能在for循环中使用,当循环中没有信息渲染时,会渲染empty下的内容)
<body>
{% for song in songs %}
<hr>
<h1>{{ song.name }}</h1>
{% empty %}
<h3>臥槽沒東西</h3>
{% endfor %}
</body>
4.当前循环值
<body>
{% for song in songs %}
<hr>
<h1>当时循环是{{ forloop.counter }}:{{ song.name }}</h1>
{% comment %}直接录入参数forloop会返回Json字符串,还可以获取其他的值,比如是否第一个{% endcomment %}
{% endfor %}
</body>
5.判断语句
<body>
{% for song in songs %}
<hr>
{% if forloop.first %}
<h1 style="color: aqua">{{ song.name }}</h1>
{% elif forloop.last%}
<h2 style="color: chartreuse">{{ song.name }}</h2>
{% else %}
<h3>{{ song.name }}</h3>
{% endif %}
{% endfor %}
</body>
6.乘除法语句(语法很奇特,想用一种方法解决乘除法,用的分子分母运算;10*5==10*一分之五;10/5==10*五分之一)
<hr>
{% comment %}乘除法函数,第一参数是基数,10*5{% endcomment %}
<h3>{% widthratio 10 1 5 %}</h3>
{% comment %}10/5{% endcomment %}
<h3>{% widthratio 10 5 1 %}</h3>
7.整除(常用于隔行显示内容也就是取余)
<body>
{% for song in songs %}
{% if forloop.counter|divisibleby:2 %}
<h3 style="color: aqua">{{ song.name }}</h3>
{% else %}
<h3>{{ song.name }}</h3>
{% endif %}
{% endfor %}
</body>
8.判断相等 (不相等就是ifnotequal)
<body>
{% for song in songs %}
{% ifequal forloop.counter 3 %}
<h3 style="color: aqua">{{ song.name }}</h3>
{% else %}
<h3>{{ song.name }}</h3>
{% endifequal %}
{% endfor %}
</body>
9.数字加减
<body>
<h3>{{ 10|add:10 }}</h3>
<h3>{{ 10|add:-10 }}</h3>
</body>
10.转大小写
<body>
<h3>{{ 'sola'|upper}}</h3>转大写
<h3>{{ 'HEHE'|lower }}</h3>转小写
</body>
11.每个字符加入间隔
<h3>{{ 'sola' | join:'屌' }}</h3>
12.给空值设置默认值
<body>
<h3>{{ '' | default:"sola" }}</h3>
</body>
13.时间转换字符串
<body>
{{ dateVal|date:'y-m-d' }}
</body>
14.回传值可渲染成html(谨慎使用)
context
context = {"songs":songs.values(),
"text":"<h1>哈哈</h1>"
}
html
<body>
{{ text|safe }}
</body>
15.于14一样的另一种
<body>
{% autoescape on %}
{{ text }} off相当于确认,可以渲染成html,on是不渲染,继续显示字符串
{% endautoescape %}
</body>