Search code examples
pythondjangopython-3.xdjango-templatesdjango-oscar

how to iterate python-django loop for N times in template?


I have an Object in python-django which i want to iterate in Django template for 5 times only, but the object has more than 100 values in it.

What i am doing is :

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

nut this will run run till all elements. want to run it 5 times only.


Solution

  • You can use the built-in 'slice' template tag:

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

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