L
L
lehubozedo2017-08-15 16:09:56
Django
lehubozedo, 2017-08-15 16:09:56

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>

how to do it with cycle - https://docs.djangoproject.com/en/1.11/ref/templat... ??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2017-08-15
@lehubozedo

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 question

Ask a Question

731 491 924 answers to any question