Reputation: 815
I want to print only 10 elements from list in Django template
here is my code
<ul>
<h3>Positive Tweets :</h3>
{% for tweet in positiveTweet %}
<li>{{ tweet.0 }}</li>
{% endfor %}
</ul>
How can I print first 10 elements if positiveTweet list having length of 100 something.
Upvotes: 14
Views: 13469
Reputation: 91
Check for the loop counter like this:
{% for tweet in positiveTweet %}
{% if forloop.counter < 11 %}
<!-- Do your something here -->
{% endif %}
{% endfor %}
Upvotes: 4
Reputation: 2993
The Django way is to construct a Paginator over the result set in the view, then look at properties of the Page in your template, see the Django pagination documentation for full details.
For instance if my News objects are available like this:
def index(request):
news = News.objects.filter(published=True).select_related('author').prefetch_related('tags')
paginator = Paginator(news, 10)
page_obj = paginator.page(request.GET.get('page', '1'))
return render(request, 'front.html', {'news': page_obj})
In the template, you are given a Page object, which will hold 10 items at a time and have several useful properties you can wire into a UI pager. For instance the bootstrap pager is wired a bit like this:
{% for post in news %}
<h3>{{ post.headline }}</h3>
{{ post.body }}
{% endfor %}
<nav>
<ul class="pagination">
{% if news.has_previous %}
<li>
<a href="?page={{news.previous_page_number}}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{% endif %}
{% for p in news.paginator.page_range %}
<li class="{% if news.number == p %}active{% endif %}"><a href="?page={{p}}">{{p}}</a></li>
{% endfor %}
{% if news.has_next %}
<li>
<a href="?page={{news.next_page_number}}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
{% endif %}
</ul>
</nav>
Upvotes: 4
Reputation: 393
Likewise, a loop that stops processing after the 10th iteration:
{% for user in users %}
{%- if loop.index >= 10 %}{% break %}{% endif %}
{%- endfor %}
loop.index starts with 1, and loop.index0 starts with 0.
Visit the below link for details: http://jinja.pocoo.org/docs/2.10/templates/#for-loop
Upvotes: -3
Reputation: 1415
You can use slice
to make this:
<ul>
<h3>Positive Tweets :</h3>
{% for tweet in positiveTweet|slice:":10" %}
<li>{{ tweet.0 }}</li>
{% endfor %}
</ul>
See the Django Slice Docs.
Upvotes: 42