Is there a way to maintain state between tag calls? I need to store the last item passed to a tag that I have created. It appeared as if I could use context to do this, but it doesn’t seem to work. Here is my code:
@register.simple_tag(takes_context=True)
def date_divider(context, date):
if 'last_date' not in context or context['last_date'] != date:
# display new date header
context['last_date'] = date
return date_header
The problem is that a new date header is always created even if the date passed in should match the date in the context.
I’m guessing I’m using context wrong here… Is there a way to store this last date in the context or is there a better way to do this?
It seems likely that the context into which you are entering
last_dateno longer exists the second time you reach this tag (for instance, perhaps that context has been popped already?). A (sort of hackish) solution is to be sure that you insertlast_dateinto the “highest” context:This kind of approach is often needed when the tags that you are writing aren’t “nested”, I’ve found. Incidentally, I’ve also found that tags of this sort are themselves often a hack!
(Not to say this particular case is, just that my cases have been).