Numeric for loop in Django templates

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

    I've used a simple technique that works nicely for small cases with no special tags and no additional context. Sometimes this comes in handy

    {% for i in '0123456789'|make_list %}
        {{ forloop.counter }}
    {% endfor %}
    
    0 讨论(0)
  • 2020-11-22 04:00

    You can pass :

    { 'n' : range(n) }

    To use template :

    {% for i in n %} ... {% endfor %}

    0 讨论(0)
  • 2020-11-22 04:01

    Just incase anyone else comes across this question… I've created a template tag which lets you create a range(...): http://www.djangosnippets.org/snippets/1926/

    Accepts the same arguments as the 'range' builtin and creates a list containing
    the result of 'range'.
    
    Syntax:
        {% mkrange [start,] stop[, step] as context_name %}
    
    For example:
        {% mkrange 5 10 2 as some_range %}
        {% for i in some_range %}
          {{ i }}: Something I want to repeat\n
        {% endfor %}
    
    Produces:
        5: Something I want to repeat 
        7: Something I want to repeat 
        9: Something I want to repeat
    
    
    0 讨论(0)
  • 2020-11-22 04:04

    You can pass a binding of

    {'n' : range(n) }
    

    to the template, then do

    {% for i in n %}
    ...
    {% endfor %}
    

    Note that you'll get 0-based behavior (0, 1, ... n-1).

    (Updated for Python3 compatibility)

    0 讨论(0)
  • 2020-11-22 04:05

    I tried very hard on this question, and I find the best answer here: (from how to loop 7 times in the django templates)

    You can even access the idx!

    views.py:

    context['loop_times'] = range(1, 8)
    

    html:

    {% for i in loop_times %}
            <option value={{ i }}>{{ i }}</option>
    {% endfor %}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题