Jieke Wei
Jieke Wei

Reputation: 183

Django - Limit the number of objects in Django template

I used to code in C#. I want to use Python to do something like:

int start_index = 4;
List<int> list = { ... }
for(int i = start_index;i < 10;i++){
     list[i].dosomething();
}

This is how I tried in Django

{% with 0 as starting_index %}
{% for comment in comments %}
<!--set a variable to limit the amount of comment on a page-->
{% with forloop.counter as index %}
{% if index < 3 %}
<div class="comment_body">
    <div class="content_block">
        <p>{{comments[index]}}</p>
    </div>
</div>
{% endif %}
{% endwith %}
{% endfor %}
{% endwith %}

This code is obviously not working. Can anybody help me with this problem? Thanks in advance!

Upvotes: 0

Views: 896

Answers (1)

rajkris
rajkris

Reputation: 1793

If you want to do this in the template you can use the built in django template tage slice:

{% for new in comments |slice:":3" %}

Slice to the number of objects you want in the template.

Upvotes: 1

Related Questions