Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 %}
like image 565
Feanor Avatar asked Aug 15 '12 06:08

Feanor


People also ask

What does {% include %} does Django?

The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.

What {% extend %} tag does?

{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

What {{ name }} means in a Django template?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


1 Answers

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>
like image 133
Manuzor Avatar answered Nov 05 '22 13:11

Manuzor