Login

{% renderonce %} template tag

Author:
corrr
Posted:
June 13, 2010
Language:
Python
Version:
1.2
Tags:
templatetag include
Score:
2 (after 2 ratings)

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

  1. Flatpage Suggester Template tag for 404 templates by bradmontgomery 5 years, 6 months ago
  2. Repeat blocks with new context / simple Jinja-like macro system by miracle2k 8 years, 1 month ago
  3. Language-aware template inclusion by bartTC 6 years, 6 months ago
  4. Make tags easier with properties by ubernostrum 8 years, 5 months ago
  5. Readonly fields on Form/Modelform by Killarny 6 years, 6 months ago

Comments

Samus_ (on June 16, 2010):

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)

#

Samus_ (on June 19, 2010):

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.