如何访问Django模板forloop中的下一个和上一个元素? [英] How to access the next and the previous elements in a Django template forloop?

查看:83
本文介绍了如何访问Django模板forloop中的下一个和上一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to get previous and next elements in Django forloop? I'm printing a list of elements and want child element to be in div-block. So I want something like this:

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

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

As you can see my problem is list[forloop.counter-1]. How can I do it?

推荐答案

您可以创建

You can create custom template filters next and previous which returns the next and the previous elements of the for loop respectively.

from django import template

register = template.Library()

@register.filter
def next(some_list, current_index):
    """
    Returns the next element of the list using the current index if it exists.
    Otherwise returns an empty string.
    """
    try:
        return some_list[int(current_index) + 1] # access the next element
    except:
        return '' # return empty string in case of exception

@register.filter
def previous(some_list, current_index):
    """
    Returns the previous element of the list using the current index if it exists.
    Otherwise returns an empty string.
    """
    try:
        return some_list[int(current_index) - 1] # access the previous element
    except:
        return '' # return empty string in case of exception

然后,您可以在模板中执行以下操作以访问下一个和上一个元素.

Then in your template you can do the following to access the next and previous elements.

{% with next_element=some_list|next:forloop.counter0 %} # assign next element to a variable
{% with previous_element=some_list|previous:forloop.counter0 %} # assign previous element to a variable

最终密码:

{% for element in list %}         
    {% with next_element=list|next:forloop.counter0 %} # get the next element 
    {% with previous_element=list|previous:forloop.counter0 %} # get the previous element 

        {% if element.is_child and not previous_element.is_child %}
            <div class="children-block">
        {% endif %}
            {{ element.title }}
        {% if element.is_child and not next_element.is_child %}
            </div>
        {% endif %}

    {% endwith %}
    {% endwith %}
{% endfor %}

这篇关于如何访问Django模板forloop中的下一个和上一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆