在Django的模板标签中使用整数进行for循环

时间:2019-11-22 20:49:19

标签: django django-templates

在我的Django模板中,{{review.stars}}是1到5的整数,但我不想显示一个简单的数字,而是要显示与{{review.stars}}整数相等的星形图标。

我应该这样写:

for n in range(1, review.stars+1):
  add star icon

但是显然我不能在Django模板标签中写类似的内容。 可变次数运行循环的pythonic方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以将范围从视图传递到模板,然后遍历模板。引用this SO answer

查看:

render_to_response('template.html', {..., 'stars': range(review.stars), ...}, ...)

模板:


{% for n in stars %}
    # add star icon
{% endfor %}