小编tet*_*fro的帖子

如何访问Django模板forloop中的下一个和前一个元素?

在Django forloop中获取前一个和下一个元素的最佳方法是什么?我正在打印一个元素列表,并希望子元素在div块中.所以我想要这样的东西:

{% for element in list %}
    {% if element.is_child and not list[forloop.counter-1].is_child %}
    <div class="children-block">
    {% endif %}
        {{ element.title }}
    {% if element.is_child and not list[forloop.counter+1].is_child %}
    </div>
    {% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

你可以看到我的问题是list[forloop.counter-1].我该怎么做?

python django templates

5
推荐指数
1
解决办法
2950
查看次数

标签 统计

django ×1

python ×1

templates ×1