-
-
Save ronnievdc/1e5c71d808a06768b862f3c5a9f9e4c0 to your computer and use it in GitHub Desktop.
Django 2 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 ctname not 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 | |
included = do_include(parser, token) | |
try: | |
included.include_path = included.template.var | |
except AttributeError: | |
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