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)
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)
| 归档时间: |
|
| 查看次数: |
20178 次 |
| 最近记录: |