【问题标题】:Slicing in Django Template在 Django 模板中切片
【发布时间】:2017-04-24 06:51:55
【问题描述】:

我有一个列表['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

在我的 django 模板中,我希望输出为

a b
c d
e f
g h

这就是我正在做的:-

{% for i in list|slice:"::2" %}
    {{i}} {{}} // how do I get the second element?
{% endfor %}

我错过了什么?

以下是python的等价物:-

for i in range(0, len(list), 2):
    print list[i], list[i+1]

【问题讨论】:

    标签: django django-templates django-template-filters


    【解决方案1】:

    除了上一个答案。你也可以使用cycle tag

    {% for el in my_list %}
        {{ el }}
        {% cycle ' ' '<br>' %}
    {% endfor %}
    

    会给你想要的输出:

    a b
    c d
    e f
    g h
    

    【讨论】:

      【解决方案2】:

      我不知道你所说的“第二个元素”是什么意思。像这样分割列表会给你['a', 'c', 'e', 'g']i 将依次是每个。

      我怀疑你根本不想这样做;您可能希望遍历整个列表并使用{% if forloop.counter|divisibleby:2 %} 来确定何时插入新段落或中断标记。

      【讨论】:

      • 嗨,Daniel,请查看更新后的问题(python 等效项)。
      • 这根本不等同。 “Python 等价物”将是 for i in lst[::2]
      • 我的错误。是的,for i in lst[::2] 会更贴切。如何在 django 模板中打印 ith 和 i+1th 索引。
      • 不能,因为i 不是索引,它是元素本身。上面已经给出了我对如何解决问题的想法。
      猜你喜欢
      • 2013-04-30
      • 2014-06-18
      • 2012-02-08
      • 2013-05-08
      • 2010-12-26
      • 2018-12-24
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      相关资源
      最近更新 更多