Yannick
Yannick

Reputation: 3663

Django Stopping loop after x times within a template

I have queryset that returns many records but in the template I use it twice to return value.

For example: On one instance I need to return the latest 5 posts and then show all the posts on that same page. So for that reason I can't use LIMIT in my queryset.

{% for post in blog_posts %}
<li>{{ post.title }}</li>
{% endfor %}

From that example how can I stop to loop after 5 times.

Upvotes: 1

Views: 70

Answers (1)

gtlambert
gtlambert

Reputation: 11971

Use the slice filter:

{% for post in blog_posts|slice:":5" %}
<li>{{ post.title }}</li>
{% endfor %}

Upvotes: 2

Related Questions