Django templates: accessing the previous and the following element of the list
django, django-templates, python
Solution
You could write a custom 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 like others have said, there are probably more elegants solutions doing this via your view
Problem
I am rather new to django templates and have an impression that I have not understood some basics. I have a list of elements and I need to render an element of the list based on conditions against the the previous and the next elements (in case the following or the previous elements are hidden, I need to mark the current element as border element). How can I reference the previous and the following elements within a `for` loop in Django templates?