I have a custom tag in Jinja2 that I want to output something only the first time that it is called. So say I have the following template:
1. {% only_once %}
2. {% only_once %}
3. {% only_once %}
I want the output to be:
1. "I only get printed once!"
2.
3.
I'm guessing the best way to do this is to set a flag in the context of the template to track whether I've already printed something or not. Here's a code sample, but is this right?
class OnlyOnceExtension(Extension):
tags = set(['only_once'])
@contextfunction
def parse(self, context, parser):
if hasattr(context, 'my_flag') and context.my_flag:
return Output("")
else:
return Output("I only get printed once!")
Is that correct? I read some stuff about the context is immutable, so will this not work? (see http://jinja.pocoo.org/2/documentation/api and search for immutable)