Django templates: accessing the previous and next list item

I am new to django templates and give the impression that I missed some of the basics.

I have a list of items and I need to display a list item based on conditions against the previous and next items (in case the next or previous items are hidden, I need to mark the current item as a border item).

How can I reference previous and next elements in a loop for

in Django templates?

+3


source to share


4 answers


You can write your own template filter for next

and previous

:

def next(value, arg):
    try:
        return value[int(arg)+1]
    except:
        return None

      

and in the template:



{% for ... %}
  {% with list|next:forloop.counter0 as next %}
    {% if next.is_hidden %}
    ...
    {% endif %} 
  {% endwith %}
{% endfor %}   

      

but as others have said, there are probably more elegant solutions doing this through your view

+11


source


You cannot do this strictly with inline template tags. You need to use some Python.

One method would be a zip

list with itself:

new = ([(None, orig[0], orig[1])] + 
       zip(orig, orig[1:], orig[2:]) + 
       [(orig[-2], orig[-1], None)])

      



and pass that to the template and then loop it like this:

{% for prev, current, next in new %}
    {% if prev.hidden or next.hidden %}
        BORDER
    {% endif %}
    {{ current }}
{% endfor %}

      

+3


source


You really shouldn't be using Django templates for this kind of logic. You have your views to deal with this. I would figure out which list items are bounds and pass an additional parameter that I can handle in the template using a simple operator if

. For example:

{% for element,is_border in data.items %}
 {% if is_border %}
   do something
 {% endif %}
{% endfor %}

      

There are several similar ways you can do this. I have provided just one example.

+1


source


You can create an external tag that does this, but django's templating system, which was built to be lightweight, doesn't have such a feature for loops.

+1


source







All Articles