'Is there a way to create a global counter variable on django templates?

I don't see any other solution other than creating a global variable counter, this counter would be then checked if it meets the criteria (let's say 9 items per page) then do a page break

Ideally, here is what I expect to do:

I have fruit_items define like this:

Class FruitVendor(Model):
    ....

@property
def fruit_items(self):
    return chain(
        self.appleitem_set.all(),
        self.bananaitem_set.all()
    )

Then in django template I do this to list:

{% for item in fruit_vendor.fruit_items %}
     {% if forloop.counter|divisibleby:9 %}
          <p style="page-break-before: always"></p>
     {% endif %}
   <table>
      {% for apple in appleitem_set.all() %} 
           <tr>
              <td>
                 {{apple.name}}
              </td>
           </tr>
      {% endfor %}
   </table>
<table>
     {% for banana in bananaitem_set.all() %} 
         <tr>
           <td>
               {{banana.name}}
           </td>
         </tr>
      {% endfor %}
 </table>
{% endfor %}

As you can see in above, this would page-break but the overhead looping of fruit_items generate multiple tables which is not intended.

What I think I should do remove the forloop in fruit_items and have a global counter that adds + 1 in each for loop, then check if the global counter is divisible by 9 then page-break, but I'm not sure if this is possible.

counter = 0

{% if counter|divisibleby:9 %}
          <p style="page-break-before: always"></p>
     {% endif %}
   <table>
      {% for apple in appleitem_set.all() %} 
           <tr>
              <td>
                 {{apple.name}}
              </td>
           </tr>
           counter += 1
      {% endfor %}
   </table>
<table>
     {% for banana in bananaitem_set.all() %} 
         <tr>
           <td>
               {{banana.name}}
           </td>
         </tr>
       counter += 1
      {% endfor %}
 </table>


Solution 1:[1]

You can give yourself a counter with a bit of python code:

class MyCount(object):
    def __init__(self):
    self.v = 0  # or 1 if you prefer it to start at 1
def bump(self):
    self.v += 1
    return ''

Pass an instance in your context

 context['counter'] = MyCount()

In your template

{% if counter.v|divisibleby:9 %}  

{{counter.bump}} will increase counter.v by one

 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nigel222