This is in the spirit of php's include_once or a C preprocessor #ifndef. Kind of. As you might've guessed, the output of
{% renderonce %}foo{% endrenderonce %}
{% renderonce %}foo{% endrenderonce %}
in a template will be a single 'foo'. I use it for js script tags personally, to prevent duplicate inclusions. If you ended up here, chances are you've already explored the "use inheritance" or "use django-(app X)" solutions, so feel free to omit such comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @register.tag
def renderonce(parser, token):
nodelist = parser.parse(('endrenderonce',))
parser.delete_first_token()
return RenderOnceNode(nodelist)
class RenderOnceNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
k = type(self)
if k not in context.render_context:
context.render_context[k] = {}
output = self.nodelist.render(context)
if output in context.render_context[k]:
output = ''
else:
context.render_context[k][output] = True
return output
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
so you did it! great :) just a few comments:
you forgot to add the imports here, I think it'll be better to have a snippet that can work without modifications when you download it instead of having only the relevant parts.
also you should mention that it requires Django 1.2 (for the render_context)
#
oh nice! they added a dropdown to select the django version the script is for, but it looks it defaulted to 1.2 which I'm fairly sure most of the scripts on the website aren't compatible with.
#
Please login first before commenting.