62π
β
The following should solve your problem, using built-in template tags :
<ul>
<li>
{% for obj in objects %}
<a>{{ obj }}</a>
{# if the the forloop counter is divisible by 4, close the <li> tag and open a new one #}
{% if forloop.counter|divisibleby:4 %}
</li>
<li>
{% endif %}
{% endfor %}
</li>
</ul>
π€Manuzor
18π
You can use the divisibleby tag as mentioned before, but for template clearing purposes I usually prefer a helper function that returns a generator:
def grouped(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
example simplistic view:
from app.helpers import grouped
def foo(request):
context['object_list'] = grouped(Bar.objects.all(), 4)
return render_to_response('index.html', context)
example template:
{% for group in object_list %}
<ul>
{% for object in group %}
<li>{{ object }}</li>
{% endfor %}
</ul>
{% endfor %}
3π
you can use divisibleby built-in filter, here is link to django documentation
so something like this would work
{% if value|divisibleby 4 %}
#your conditional code
{% endif %}
π€Vaibhav Mishra
- {% load static %} and {% load staticfiles %}: which is preferred?
- Django order items by two fields, but ignoring them if they're zero
- How can I make SSE with Python (Django)?
- How do you use Django-filter's '__in' lookup?
2π
if you want to work it with checking first forloop and last forloop you could use this :
<ul>
{% for obj in objects %}
{% if forloop.first %}
<li>
{% endif %}
<a>{{obj}}</a>
{% if forloop.counter|divisibleby:4 and not forloop.first %}
</li>
<li>
{% endif %}
{% if forloop.last %}
</li>
{% endif %}
{% endfor %}
</ul>
π€Yuda Prawira
- Django admin β select reverse foreign key relationships (not create, I want to add available)
- How to append pages of data using jQuery and Django pagination?
- Managing multiple settings.py files
1π
I personally would consider to separate the elements in the view before passing them to the template and then using nested for loops. Except this you really only have the filter or templatetag option as Vaibhav Mishra mentioned.
- How to embed matplotlib graph in Django webpage?
- Django prefetch_related's Prefetch, order_by?
- Celery β No module named five
Source:stackexchange.com