Shufi123
Shufi123

Reputation: 233

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?

Upvotes: 0

Views: 1240

Answers (2)

Andrey Borzenko
Andrey Borzenko

Reputation: 738

You can do:

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

Upvotes: 3

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

Try:

{% with new_list=list|slice":5" %}
    {% for item in new_list %} 
        <h1>Check</h1>
    {% endfor %}
{% endwith %}

See: django_template_with and django_template_slice

Upvotes: 1

Related Questions