[Django]-Django templates: accessing the previous and the following element of the list

11๐Ÿ‘

โœ…

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

๐Ÿ‘คTimmy O'Mahony

3๐Ÿ‘

You canโ€™t do this strictly with built-in template tags. You need to involve some Python.

One method would be to zip the 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, then loop over it like this:

{% for prev, current, next in new %}
    {% if prev.hidden or next.hidden %}
        BORDER
    {% endif %}
    {{ current }}
{% endfor %}
๐Ÿ‘คagf

1๐Ÿ‘

You really shouldnโ€™t use the Django templates for this kind of logic. You have your views to handle it. I would figure out which elements of the list are borders and pass in an extra parameter that I can handle in the template using a simple if statement. For example:

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

There are tons of similar ways you can do this. I presented just one example.

๐Ÿ‘คMihai Oprea

1๐Ÿ‘

You can create an external tag which does that but django templating system which was build to be lightweight has no such feature in for loops.

๐Ÿ‘คluke14free

Leave a comment