简体   繁体   中英

Django iterate queryset just n number of times in templates

My issue is quite simple. I am using Django taggit.

I want to iterate this only 2 times. Means to display only 4 tags in templates.

 {% for tag in data.tags.all %}
     {{tag}}                            
 {% endfor %}

I have tried this, but it is not making any sense:

 {% for tag in data.tags.all|ljust:"2" %}
    {{tag}}                            
 {% endfor %}

Can anyone suggest how can I achieve it?

You can make use of the |slice template filter [Django-doc] :

{% for tag in data.tags.all %}
    {{ tag }}                            
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM