Django模板{%for%}标记每隔第4个元素添加li

Fea*_*nor 17 django django-templates

我需要在模板中表示集合并包装中的每四个元素

<li></li>
Run Code Online (Sandbox Code Playgroud)

模板应该是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

所以我需要在{%for%}中这样做

{% for obj in objects %}
 {#add at 1th and every 4th element li wrap somehow#}
    <a>{{object}}</a>
 {# the same closing tag li#}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

Man*_*zor 55

以下应使用内置模板标记解决您的问题:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 我真的不喜欢这种在条件满足时注入关闭标签的程序方式。请参阅响应http://stackoverflow.com/a/11965885/636626,以获取更具可读性和可重用性的解决方案。 (2认同)

Hed*_*ide 17

您可以使用前面提到的divisibleby标记,但出于模板清除的目的,我通常更喜欢返回生成器的辅助函数:

def grouped(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]
Run Code Online (Sandbox Code Playgroud)

示例简单化视图:

from app.helpers import grouped

def foo(request):
    context['object_list'] = grouped(Bar.objects.all(), 4)
    return render_to_response('index.html', context)
Run Code Online (Sandbox Code Playgroud)

示例模板:

{% for group in object_list %}
   <ul>
        {% for object in group %}
            <li>{{ object }}</li>
        {% endfor %}
   </ul>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)