• 技术文章 >Python框架 >Django

    Django中template for如何使用?

    小P小P2020-11-15 18:40:58原创4908

    之前我们讲过很多次for循环了,python中的循环有不少,不知道有没有听过template for这个循环,这个也算是for循环的这一种延伸。

    也许有的小伙伴对template for的用法不是很明确,借着这个机会,今天来讲讲新朋友template for循环。 当列表为空或者非空时执行不同操作:

    1

    2

    3

    4

    5

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">{% for item in list %}

        ...

    {% empty %}

        ...

    {% endfor %}<br></span></p>


    使用forloop.counter访问循环的次数,下面这段代码依次输出循环的次数,从1开始计数:


    1

    2

    3

    4

    5

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">{% for item in list %}

        ...

        {{ forloop.counter }}

        ...

    {% endfor %}<br></span></p>

    从0开始计数:


    1

    2

    3

    4

    5

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">{% for item in list %}

        ...

        {{ forloop.counter0 }}

        ...

    {% endfor %}<br></span></p>


    判断是否是第一次循环:


    1

    2

    3

    4

    5

    6

    7

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">{% for item in list %}

        ...

        {% if forloop.first %}

            This is the first round.

        {% endif %}

        ...

    {% endfor %}<br></span></p>


    判断是否是最后一次循环:


    1

    2

    3

    4

    5

    6

    7

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">{% for item in list %}

        ...

        {% if forloop.last %}

            This is the last round.

        {% endif %}

        ...

    {% endfor %}<br></span></p>


    逆向循环:


    1

    2

    3

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 14px;">{% for item in list reversed %}

        {{ item }}

    {% endfor %}<br></span></p>


    以上就是Django中template for循环使用的使用方法,跟for循环相比较有什么不同呢?小伙伴们恶意找出来再跟小编进行交流。更多Python学习推荐:PyThon学习网教学中心

    专题推荐:templatefor使用;django
    上一篇:Django中如何用xlwt导出文件 下一篇:Django中in和not in的用法

    相关文章推荐

    • pycharm新建django项目时报错• pycharm不支持django的解决方法• Django中如何用xlwt生成表格• Django中如何用xlwt导出文件

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网