Created
May 3, 2013 07:18
-
-
Save gdugas/5507702 to your computer and use it in GitHub Desktop.
Django template tag: include_once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
register = template.Library() | |
def render_include_once(self, context): | |
ctname = '_include_once_node_registry' | |
if not ctname in context: | |
context[ctname] = {} | |
if not self.include_path or self.include_path in context[ctname]: | |
return "" | |
else: | |
context[ctname][self.include_path] = True | |
return self._render_origin(context) | |
@register.tag(name='include_once') | |
def do_include_once(parser, token): | |
import types | |
from django.template.loader_tags import (do_include, | |
ConstantIncludeNode, | |
IncludeNode) | |
included = do_include(parser, token) | |
if isinstance(included, ConstantIncludeNode): | |
try: | |
included.include_path = included.template.name | |
except: | |
included.include_path = None | |
elif isinstance(included, IncludeNode): | |
included.include_path = included.template_name | |
else: | |
included.include_path = None | |
included._render_origin = included.render | |
included.render = types.MethodType(render_include_once, included) | |
return included |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment