Django模板{%for%}标签添加每个第4个元素 [英] Django template {%for%} tag add li every 4th element

查看:359
本文介绍了Django模板{%for%}标签添加每个第4个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在模板中表示集合,并将

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

<li></li>

模板应该是这样的:

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

所以我需要在{%for%}中执行

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 %}


推荐答案

以下内容可以解决您的问题,使用内置的模板标签:

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>

这篇关于Django模板{%for%}标签添加每个第4个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆