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.
One can loop over a list in reverse by using {% for obj in list reversed %} .
{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.
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.
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>
Check for the loop counter like this:
{% for tweet in positiveTweet %}
{% if forloop.counter < 11 %}
<!-- Do your something here -->
{% endif %}
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With