Django 循环模板标签

发布于:2024-06-26 ⋅ 阅读:(48) ⋅ 点赞:(0)

1,循环模板标签

Django 模板系统中提供了多种循环模板标签来迭代数据并显示列表、字典或其他可迭代对象。

1.2 {% for %} 标签

用于迭代列表或可迭代对象,并为每个元素提供上下文变量。

{% for item in items %}
    {{ item }} <!-- 渲染当前迭代项 -->
{% endfor %}

1.3 {% for %} 与索引

在迭代时,可以使用 forloop.counter 访问当前迭代的索引(从1开始)。

{% for item in items %}
    {{ forloop.counter }}: {{ item }}
{% endfor %}

1.4 {% for %} 与反转索引

使用 forloop.revcounter 访问当前迭代的反转索引(从列表长度开始递减)。

{% for item in items %}
    {{ forloop.revcounter }}: {{ item }}
{% endfor %}

1.5 {% for %} 与迭代次数

使用 forloop.last 判断当前迭代是否是最后一次迭代。

{% for item in items %}
    {{ item }}
    {% if not forloop.last %}, {% endif %}
{% endfor %}

1.6 {% empty %} 标签

如果被迭代的变量为空或不存在,将渲染 {% empty %} 标签和与之对应的 {% endfor %} 之间的内容。

{% for item in items %}
    {{ item }}
{% empty %}
    <!-- 没有可迭代的项目时渲染 -->
    No items to display.
{% endfor %}

1.7{% for %} 与字典

当迭代字典时,可以使用 forloop.counter0 和 forloop.counter 访问键和值。

{% for key, value in my_dict.items %}
    {{ key }}: {{ value }}
{% endfor %}

示例:

2,添加HTML代码

Test/templates/4/for_demo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<table border="1">
    {% for list in lists %}

        {% if forloop.first %}
        <tr>
            <td>
                第一个值:{{ list.书名 }}
            </td>
        </tr>
        {% endif %}

        <tr>
            <td>
                当前值:{{ list.书名 }}, 价格:{{ list.价格 }}, 当前正序索引:{{ forloop.counter0 }}, 当前倒序索引:{{ forloop.revcounter0 }}
            </td>
        </tr>

        {% if forloop.last %}
        <tr>
            <td>
                最后一个值:{{ list.书名}}
            </td>
        </tr>
        {% endif %}


    {% endfor %}

</table>

</body>
</html>

3,添加视图函数

Test/app4/views.py

from django.shortcuts import render

# Create your views here.
def var(request):
    name = '小6'

    # 列表对象
    lists = ['java', 'python', 'c', 'c++', 'js']

    # 字典对象
    dicts = {'姓名': '小强', '年龄':25, '性别':'男'}

    return render(request, '4/var.html', {'lists': lists, 'dicts': dicts, 'name':name})

def if_demo(request):
    age = 18

    return render(request, '4/if_demo.html', {'age':age})

def for_demo(request):
    dict1 = {'书名':'Django开发教程', '价格':28, '作者':'小强'}
    dict2 = {'书名':'java开发教程', '价格':38, '作者':'小红'}
    dict3 = {'书名':'python开发教程', '价格':48, '作者':'小6'}
    dict4 = {'书名':'c开发教程', '价格':58, '作者':'小7'}

    lists = [dict1, dict2, dict3, dict4]
    return render(request, '4/for_demo.html', {'lists':lists})

4,添加路由地址

Test/app4/urls.py

5,访问页面

http://127.0.0.1:8000/app4/for_demo


网站公告

今日签到

点亮在社区的每一天
去签到