Search code examples
pythondjangodjango-templatesdjango-3.0django-3.1

How to make a ranged for loop that iterates over elements in a list in Django


I'm fairly new to Django 3, but I could not find any answer that shows the best way to use Django template syntax in order to iterate over the first five elements in a list given in the context.

For clarification, what I'm looking for is a way to do this:

(given the following list in the context["one", "two", "three", "four", "five", "six"]) I want to display the first five elements in a way similar to this vanilla Python code:

for item in range(5):
    print(list[item])

I would even appreciate it if someone could try and show my how to break a loop in the templates (if it's even possible). Is there a way to do any one of these?


Solution

  • You can do:

    {% for item in list%}
        {% if forloop.counter < 6}
            // Do what you need
        {% endif %}
    {% endfor %}