Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a list with django template tags

I have a single list my_list in my context, and I'd like to render it as two "columns", with the first (n+1)/2 items in the first column and the last n/2 items in the second column. Is there a straight-forward way to do this with django template tags/filters or do I need to pre-split the list into two in my view?

e.g.,

<div class="split-50-left">
  <ul> 
    {% for item in [first half of my_list] %}
      <li>{{item}}</li>
    {% endfor %}
  </ul>
</div>
<div class="split-50-right">
  <ul> 
    {% for item in [second half of my_list] %}
      <li>{{item}}</li>
    {% endfor %}
  </ul>
</div>
like image 751
B Robster Avatar asked Jul 30 '13 15:07

B Robster


1 Answers

The more 'Django' way would be to do it in the view, as you are supposed to keep as much logic out of your template as possible. That being said, there is a ways you can do it through the template.

You can use the slice template tag if you already know how many are in the list. Let's assume you don't though.

The other method would be to just loop over it twice, and only display half you want. You would be going over the entire list though each time, so it might be expensive. It uses the forloop counter.

{% for item in items %}
#half list is calculated in your view. It is the items query /2
   {% if forloop.counter < half_list %}
       {% item.name %}
   {% endif %}
{% endfor %}

{% for item in items %}
#half list is calculated in your view. It is the items query /2
    {% if forloop.counter >= half_list %}
        {% item.name %}
    {% endif %}
{% endfor %}
like image 184
JcKelley Avatar answered Oct 05 '22 22:10

JcKelley