[Fixed]-Add limit for list in for loop django template


You can use slice to make this:

    <h3>Positive Tweets :</h3>
    {% for tweet in positiveTweet|slice:":10" %}
      <li>{{ tweet.0 }}</li>
    {% endfor %}

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 %}

  <ul class="pagination">
    {% if news.has_previous %}
      <a href="?page={{news.previous_page_number}}" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
    {% 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 %}
      <a href="?page={{news.next_page_number}}" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
    {% endif %}


Check for the loop counter like this:

          {% for tweet in positiveTweet %}

               {% if forloop.counter < 11 %}

                <!-- Do your something here -->

               {% endif %}

          {% endfor %}


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

Leave a comment