if语句
>格式
{% if 条件表达式1 %}
…
{% elif 条件表达式2 %}
…
{% elif 条件表达式3 %}
…
{% else %}
…
{% endif %}
>示例
view端
def mytemp_view(request):
x = 6
return render(request, "mytemp.html", locals())
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模板标签</title>
</head>
<body>
{% if x > 0 %}
<h1>{
{x}}大于0</h1>
{% elif x == 0 %}
<h1>{
{x}}等于0</h1>
{% elif x < 0 %}
<h1>{
{x}}小于0</h1>
<!-- 结束标签 -->
{% endif %}
</body>
</html>
显示
for语句
>格式
{% for 变量 in 可迭代对象 %}
… 循环语句
{% empty %}
… 可迭代对象无数据时填充的语句
{% endfor %}
变量 | 描述 |
---|---|
forloop.counter | 循环的当前迭代(从1开始索引) |
forloop.counter0 | 循环的当前迭代(从0开始索引) |
forloop.revcounter | 循环结束的迭代次数(从1开始索引) |
forloop.revcounter0 | 循环结束的迭代次数(从0开始索引) |
forloop.first | 如果这是第一次通过循环,则为真 |
forloop.last | 如果这是最后一次循环,则为真 |
forloop.parentloop | 当嵌套循环,parentloop 表示外层循环 |
>示例
view端
def for_view(request):
lst = ['北京', '上海', '广州', '深圳']
return render(request, 'for.html', locals())
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>列表的使用</title>
</head>
<body>
<ul>
{% for city in lst %}
{% if forloop.first %} <li>=======</li>{% endif %}
<li>{
{ forloop.counter }}、{
{ city }}</li>
{% if forloop.last %} <li>-------</li>{% endif %}
{% empty %}
<li>没有城市</li>
{% endfor %}
</ul>
</body>
</html>
显示
过滤器
>格式
{ { 变量 | 过滤器1:参数值1 | 过滤器2:参数值2 … }}
过滤器 | 说明 |
---|---|
lower | 将字符串转换为全部小写。 |
upper | 将字符串转换为大写形式 |
safe | 默认不对变量内的字符串进行html转义 |
add: “n” | 将value的值增加 n |
truncatechars:‘n’ | 如果字符串字符多于指定的字符数量,那么会被截断。 截断的字符串将以可翻译的省略号序列(“…”)结尾。 |
… |
>示例
view端
def for_view(request):
s = "<i>Hello World!</i>"
n = 100
s2 = "aa bb cc dd ee ff"
return render(request, 'for.html', locals())
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>过滤器</title>
</head>
<body>
<div>
<h2>s = {
{ s }}</h2>
<h2>s | safe = {
{s | safe }}</h2>
<!-- 大写过滤器 -->
<h2>s | upper = {
{s | upper }}</h2>
<h2>s | lower = {
{s | lower }}</h2>
<h5>n + 2 = {
{ n | add:'2' }}</h5>
<h5>s2 = {
{ s2 }} </h5>
<h5>s2 | truncatechars:8 = {
{ s2 | truncatechars:'8' }} </h5>
</div>
</body>
</html>
显示