Skip to content

Instantly share code, notes, and snippets.

@ronnievdc
Forked from gdugas/include_once.py
Last active September 23, 2020 14:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronnievdc/1e5c71d808a06768b862f3c5a9f9e4c0 to your computer and use it in GitHub Desktop.
Save ronnievdc/1e5c71d808a06768b862f3c5a9f9e4c0 to your computer and use it in GitHub Desktop.
Django 2 template tag: include_once
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