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

tet*_*fro 5 python django templates

在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].我该怎么做?

Rah*_*pta 8

您可以创建自定义模板过滤器 next,previous并返回for循环的下一个和前一个元素.

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
Run Code Online (Sandbox Code Playgroud)

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

{% 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
Run Code Online (Sandbox Code Playgroud)

最终守则:

{% 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 %}
Run Code Online (Sandbox Code Playgroud)