Django - 在模板的for循环中迭代数字 [英] Django - iterate number in for loop of a template

查看:39
本文介绍了Django - 在模板的for循环中迭代数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 django 模板中有以下 for 循环显示天数.我想知道,是否可以在循环中迭代一个数字(在下面的情况下 i).还是必须先存到数据库中,然后以days.day_number的形式查询?

I have the following for loop in my django template displaying days. I wonder, whether it's possible to iterate a number (in the below case i) in a loop. Or do I have to store it in the database and then query it in form of days.day_number?

{% for days in days_list %}
    <h2># Day {{ i }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

推荐答案

Django 提供了它.您可以使用:

Django provides it. You can use either:

  • {{ forloop.counter }} 索引从 1 开始.
  • {{ forloop.counter0 }} 索引从 0 开始.
  • {{ forloop.counter }} index starts at 1.
  • {{ forloop.counter0 }} index starts at 0.

在模板中,您可以:

{% for item in item_list %}
    {{ forloop.counter }} # starting index 1
    {{ forloop.counter0 }} # starting index 0

    # do your stuff
{% endfor %}

更多信息:for |内置模板标签和过滤器 |Django 文档

这篇关于Django - 在模板的for循环中迭代数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆