How to do a FOR or loop that start on X and end Y index of a list on Django Template Languge?

For example i have a list of 10 objects but i just want to get last 5 or the first 5 objects.

{% for x in objects %}
.....first 5 objects......
{% endfor %}

{% for x in objects %}
.....last 5 objects......
{% endfor %}

Upvotes: 0

Views: 144

Answers (2)

BottleZero
BottleZero

Reputation: 973

  • You could consider using a custom template tag.

  • Could loop through objects:

    {% for x in objects %}
        {% if forloop.counter <= 5 %}
            # ....do something....
        {% endif %}
    {% endfor %}
    
    {% for x in objects %}
        {% if forloop.revcounter <= 5 %}
            # ....do something....
        {% endif %}
    {% endfor %}
    
  • You could get the items directly (Assuming the length of objects doesn't change when displaying last 5 in list.):

    {{ objects.0 }}
    {{ objects.1 }}
    {{ objects.2 }}
    ...
    {{ objects.7 }}
    {{ objects.8 }}
    {{ objects.9 }}
    

Upvotes: 1

nik_m
nik_m

Reputation: 12086

First method (forloop.counter):

{% for x in objects %}
    {% if forloop.counter <= 5 %}
        access first 5 objects
    {% else %}
        access last 5 objects
    {% endif %}
{% endfor %}

Second method:

# views.py

def my_view(request):
    first_five_obj = MyModel.objects.all()[:5]
    last_five_obj = MyModel.objects.all()[-5:]
    return render(request, 'template.html', locals())

<!-- template.html -->

{% for x in first_five_obj %}
    .....first 5 objects......
{% endfor %}

{% for x in last_five_obj %}
    .....last 5 objects......
{% endfor %}

Upvotes: 2

Related Questions