使用django模板标签拆分列表

时间:2013-07-30 15:38:41

标签: django django-templates

我的上下文中有一个列表my_list,我想将它呈现为两个“列”,第一列中的第一个(n + 1)/ 2个项目和最后一个列/第2列中的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>

4 个答案:

答案 0 :(得分:9)

更多&#39; Django&#39;方法是在视图中执行它,因为您应该尽可能多地保留模板中的逻辑。话虽如此,有一种方法可以通过模板来实现。

如果你已经知道列表中有多少,你可以使用slice template tag。我们假设你没有。

另一种方法是将它循环两次,只显示你想要的一半。您每次都会浏览整个列表,因此可能会很昂贵。它使用forloop counter

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

答案 1 :(得分:1)

在模板中完全执行此操作的一种(略微hacky)方法是使用 widthratio 模板标记来计算列表的中心,并使用 with 模板标记创建临时变量。

{% widthratio form.visible_fields|length 2 1 as visible_fields_centre %}
<div class="rows_form">
    {% with ":"|add:visible_fields_centre as first_slice %}
        {% for field in form.visible_fields|slice:first_slice %}
            {{ field }}
        {% endfor %}
    {% endwith %}
</div>
<div class="rows_form">
    {% with visible_fields_centre|add:":" as second_slice %}
        {% for field in form.visible_fields|slice:second_slice %}
            {{ field }}
        {% endfor %}
    {% endwith %}
</div>

答案 2 :(得分:1)

如果你可以插入两半 - 或者如果分割中间并不重要 - 你可以单独渲染替代值。这会更便宜:

<ul><!-- Half of the list -->
    {% for i in values %}
        {% cycle 'odd' 'even' as state silent %}
        {% if state == 'odd' %}
            <li>{{ i }}</li>
        {% endif %}
    {% endfor %}
</ul>

<ul><!-- The other half -->
    {% for i in values %}
        {% cycle 'odd' 'even' as state silent %}
        {% if state == 'even' %}
            <li>{{ i }}</li>
        {% endif %}
    {% endfor %}
</ul>

答案 3 :(得分:0)

使用CSS完全有意义吗?我相信它会everywhere except IE9有效。

for layer in tqdm(model.layers):
    if layer.weights:
        weights = []
        for w in layer.weights:
            weight_name = os.path.basename(w.name).replace(':0', '')
            weight_file = layer.name + '_' + weight_name + '.npy'
            weight_arr = np.load(numpy_weight_file)

        # remove the "background class"
        if weight_file.startswith('Logits_bias'):
            weight_arr = weight_arr[1:]
        elif weight_file.startswith('Logits_kernel'):
            weight_arr = weight_arr[:, 1:]

        weights.append(weight_arr)
    layer.set_weights(weights)
model.save_weights("Keras_model.h5")

然后是CSS:

<ul class="two-columns">
{% for item in object_list %}
  <li>{{ item }}</li>
{% endfor %}
</ul>