Django template {%for%} tag add li every 4th element

Viewed 24510

I need to represent collection in the template and wrap every four elements in the

<li></li>

The template should be like this:

<ul>
    <li>
         <a></a>
         <a></a>
         <a></a>
         <a></a>
    </li>
    <li>
         <a></a>
         <a></a>
         <a></a>
         <a></a>
    </li>
    <li>
         <a></a>
         <a></a>
         <a></a>
         <a></a>
    </li>
</ul>

So i need to do it in the {% for %}

{% for obj in objects %}
 {#add at 1th and every 4th element li wrap somehow#}
    <a>{{object}}</a>
 {# the same closing tag li#}
{% endfor %}
5 Answers

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>
Related