Skip to content

Instantly share code, notes, and snippets.

@jamesbrobb
Last active November 6, 2020 15:59
Show Gist options
  • Save jamesbrobb/b79320205e5ab7b6766d to your computer and use it in GitHub Desktop.
Save jamesbrobb/b79320205e5ab7b6766d to your computer and use it in GitHub Desktop.
Overriding Django's {% extends %} template tag to prevent a parent template rendering in a third party app
"""
This needs to go somewhere that will force it to run immediately.
As the 'extends' tag always has to be first in a template, it's not
possible to use the {% load %} tag for this. Instead it must be
loaded in the same way as the django tags.
add_to_builtins function changed module in 1.7
"""
try:
from django.template.loader import add_to_builtins
except ImportError:
from django.template.base import add_to_builtins
add_to_builtins('my_app.templatetags.overriden_tags')
from django import template
from django.template.loader_tags import do_extends, ExtendsNode
register = template.Library()
@register.tag('extends')
def preventable_extends(parser, token):
node = do_extends(parser, token)
return PreventableExtendsNode(node.nodelist, node.parent_name)
class PreventableExtendsNode(ExtendsNode):
def render(self, context):
prevent = context.get('prevent_extends')
if prevent == self.parent_name.var:
return self.nodelist.render(context)
return super(PreventableExtendsNode, self).render(context)
class PreventExtendsMixin(object):
def __init__(self, **kwargs):
self.prevent_extends = kwargs.pop('prevent_extends')
super(PreventExtendsMixin, self).__init__(**kwargs)
def get_context_data(self, **kwargs):
context = super(PreventExtendsMixin, self).get_context_data(**kwargs)
context['prevent_extends'] = self.prevent_extends
return context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment