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
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 %}
- [Django]-Renderer returned unicode, and did not specify a charset value
- [Django]-Django url rewrite without redirect
- [Django]-Error when creating admin in django tutorial
- [Django]-Jenkins not failing on tests that fail in coverage
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.
- [Django]-How to mark string for translation in jinja2 using trans blocks
- [Django]-Output log file through Ajax in Django
- [Django]-Django RuntimeError: maximum recursion depth exceeded
- [Django]-Problem rendering a Django form field with different representation
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.
- [Django]-Return data in httpresponse for ajax call in Deleteview in django?
- [Django]-Building pluggable apps: how to include forks of popular libraries and prevent name conflicts?