Ben*_*rts 7 django django-templates
我my_list 在上下文中有一个列表,我想将它呈现为两个"列",第一列中的第一个(n + 1)/ 2项和第二列中的最后一个n/2项.有没有一种直接的方法来使用django模板标签/过滤器,或者我需要在我的视图中预先将列表拆分为两个?
例如,
<div class="split-50-left">
<ul>
{% for item in [first half of my_list] %}
<li>{{item}}</li>
{% endfor %}
</ul>
</div>
<div class="split-50-right">
<ul>
{% for item in [second half of my_list] %}
<li>{{item}}</li>
{% endfor %}
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
更多'Django'方式是在视图中执行它,因为您应该尽可能多地保留模板中的逻辑.话虽这么说,有一种方法可以通过模板来实现.
如果您已经知道列表中有多少个,则可以使用切片模板标记.我们假设你没有.
另一种方法是将它循环两次,并且只显示你想要的一半.你每次都会浏览整个列表,所以它可能很昂贵.它使用forloop计数器.
{% for item in items %}
#half list is calculated in your view. It is the items query /2
{% if forloop.counter < half_list %}
{% item.name %}
{% endif %}
{% endfor %}
{% for item in items %}
#half list is calculated in your view. It is the items query /2
{% if forloop.counter >= half_list %}
{% item.name %}
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)