Answer the question
In order to leave comments, you need to log in
How to correctly split a list into 2 parts in django templates?
There is a list like:
['Калина', 'Брусника', 'Ежевика', 'Смородина', 'Черника',]
you need to split it into two parts with a template engine, the order is NOT important (let them change places, don't care):<div class="sub-menu">
<ul>
<li><a href="#"><span>Калина</span></a></li>
<li><a href="#"><span>Брусника</span></a></li>
<li><a href="#"><span>Черника</span></a></li>
</ul>
<ul>
<li><a href="#"><span>Смородина</span></a></li>
<li><a href="#"><span>Ежевика</span></a></li>
</ul>
<div class="clear"></div>
Answer the question
In order to leave comments, you need to log in
There is no way to do this with the built-in tools of the template engine, and especially with the help of cycle. But it's easy to write a simple filter for this purpose:
from django import template
register = template.Library()
@register.filter(is_safe=True)
def chunk_list(value, chunk_size=3):
for i in range(0, len(value), chunk_size):
yield value[i:i+chunk_size]
{% load chunkify %}
{% with item_list|chunk_list:3 as chunks %}
{% for chunk in chunks %}
<ul>
{% for item in chunk %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endfor %}
{% endwith %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question