开发者

How to loop X times in Django?

I have user reviews on my site. Each review has a rating of 1-5 stars. I want to print that many stars. How do I do it? I only see {% for X in Y %} which lets you it开发者_开发百科erate over a list, but not a certain number of times.


Use the Template range filter by zalun:

from django.template import Library

register = Library()

@register.filter
def get_range( value ):
  """
    Filter - returns a list containing range made from given value
    Usage (in template):

    <ul>{% for i in 3|get_range %}
      <li>{{ i }}. Do something</li>
    {% endfor %}</ul>

    Results with the HTML:
    <ul>
      <li>0. Do something</li>
      <li>1. Do something</li>
      <li>2. Do something</li>
    </ul>

    Instead of 3 one may use the variable set in the views
  """
  return range( value )


No need for a custom filter - make_list will do the job:

{% for i in '123'|make_list %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜