I want to perform reduce the value of forloop.counter in django template for the given condition, is it possible in django.
Below is demonstrated the example
{% for i in item %}
{% if forloop.counter0|divisibleby:4 %}
Start
{% endif %}
{% if i %}
item{{ forloop.counter }}
{% else %}
######### Here I want to reduce value of forloop.counter by 1 ###########
{% endif %}
{% if forloop.counter|divisibleby:4 %}
End
{% endif %}
{% endfor %}
In above code for 8 perfect item output will be
Start
item1
item2
item3
item4
End
Start
item5
item6
item7
item8
End
but suppose item2 is None, then output is
Start
item1
item3
item4
End
Start
item5
item6
item7
item8
End
I want to print it in form of proper ascending order (incremented by 1 at each step) by reducing value of forloop each time if condition is not satisfied. Please don't suggest about the custom template tag, I know that and I consider it as last option.
I really doubt django will let you mess with forloop.counter
that easily, and wouldn't mess with it anyway. The obvious solution would be to filter out your list before you iterate over it, which can be done in your view or (if you insist on doing it in the template) using a custom filter.
Or you can wrap your list in a generator function that will take care of filtering and numbering, ie:
def filteriternum(seq):
num = 0
for item in seq:
if not item:
continue
num += 1
yield num, item
Here again, you can either do the wrapping in your view or write a custom template filter of tag that will do the wrapping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With