Numeric for loop in Django templates

后端 未结 19 887
温柔的废话
温柔的废话 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:15

    This method supports all the functionality of the standard range([start,] stop[, step]) function

    /templatetags/range.py

    from django import template
    
    register = template.Library()
    
    
    @register.filter(name='range')
    def _range(_min, args=None):
        _max, _step = None, None
        if args:
            if not isinstance(args, int):
                _max, _step = map(int, args.split(','))
            else:
                _max = args
        args = filter(None, (_min, _max, _step))
        return range(*args)
    

    Usage:

    {% load range %}
    
    

    stop 5 {% for value in 5|range %} {{ value }} {% endfor %}

    start 5 stop 10 {% for value in 5|range:10 %} {{ value }} {% endfor %}

    start 5 stop 10 step 2 {% for value in 5|range:"10,2" %} {{ value }} {% endfor %}

    Output

    stop 5 0 1 2 3 4

    start 5 stop 10 5 6 7 8 9

    start 5 stop 10 step 2 5 7 9

提交回复
热议问题