Numeric for loop in Django templates

后端 未结 19 1072
温柔的废话
温柔的废话 2020-11-22 03:29

How do I write a numeric for loop in a Django template? I mean something like

for i = 1 to n
19条回答
  •  离开以前
    2020-11-22 04:07

    I'm just taking the popular answer a bit further and making it more robust. This lets you specify any start point, so 0 or 1 for example. It also uses python's range feature where the end is one less so it can be used directly with list lengths for example.

    @register.filter(name='range')
    def filter_range(start, end):
      return range(start, end)
    

    Then in your template just include the above template tag file and use the following:

    {% for c in 1|range:6 %}
    {{ c }}
    {% endfor %}
    

    Now you can do 1-6 instead of just 0-6 or hard coding it. Adding a step would require a template tag, this should cover more uses cases so it's a step forward.

提交回复
热议问题