【问题标题】:how to iterate python-django loop for N times in template?如何在模板中迭代 python-django 循环 N 次?
【发布时间】:2017-10-13 23:20:21
【问题描述】:

我在 python-django 中有一个对象,我只想在 Django 模板中迭代 5 次,但该对象中有超过 100 个值。

我正在做的是:

  {% for x in abc %}
     <h4>{{x.name}}</h4>    
  {% endfor %}

nut 这将一直运行到所有元素。只想运行 5 次。

【问题讨论】:

标签: python django python-3.x django-templates django-oscar


【解决方案1】:

您可以使用内置的'slice'模板标签:

{% for x in abc|slice:":5" %}
   <h4>{{x.name}}</h4>    
{% endfor %}

https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#slice

【讨论】:

    最近更新 更多