Resetting a cycle tag in Jinja
At my current client I’m working on a platform that uses Django, and a templating system called Jinja.
I had to use Jinja to change the CSS class to modify the background color for each dynamic data returned in each loop.
This seems straight forward after looking at Jinja’s documentation using the cycle tag.
So, the code looked like this:
and then the class in each loop look like this:
Each loop… that’s when I ran into an issue. We had more than one loop on one page, but we needed to have the class change, and increment by 1.
It was incrementing by 1, but not resetting after each loop. So, if 3 were in the first loop the next loop would start with 4, and not reset until after 5.
So, here is an example of resetting a cycle tag in Jinja:
By calling the cycle and using .reset() this returns none, and resets the cycle.
You will noticed I have commented out {{ row_class.reset() }} without comment tags this will render “None”. So, the hack is to just comment this out.