Numeric for loop in Django templates

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

    You don't pass n itself, but rather range(n) [the list of integers from 0 to n-1 included], from your view to your template, and in the latter you do {% for i in therange %} (if you absolutely insist on 1-based rather than the normal 0-based index you can use forloop.counter in the loop's body;-).

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

    This essentially requires a range function. A Django feature ticket was raised (https://code.djangoproject.com/ticket/13088) for this but closed as "won't fix" with the following comment.

    My impression of this idea is that it is trying to lead to programming in the template. If you have a list of options that need to be rendered, they should be computed in the view, not in the template. If that's as simple as a range of values, then so be it.

    They have a good point - Templates are supposed to be very simple representations of the view. You should create the limited required data in the view and pass to the template in the context.

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

    Unfortunately, that's not supported in the Django template language. There are a couple of suggestions, but they seem a little complex. I would just put a variable in the context:

    ...
    render_to_response('foo.html', {..., 'range': range(10), ...}, ...)
    ...
    

    and in the template:

    {% for i in range %}
         ...
    {% endfor %}
    
    0 讨论(0)
  • 2020-11-22 04:12

    Maybe like this?

    {% for i in "x"|rjust:"100" %}
    ...
    {% endfor %}
    
    0 讨论(0)
  • 2020-11-22 04:12

    For those who are looking to simple answer, just needing to display an amount of values, let say 3 from 100 posts for example just add {% for post in posts|slice:"3" %} and loop it normally and only 3 posts will be added.

    0 讨论(0)
  • 2020-11-22 04:12
    {% for i in range(10) %}
       {{ i }}
    
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题