這是我真正需要的...
Any way to make {% extends '...' %} conditional? - Django
...以下是解決方案,我花了幾個小時來了,直到我終於意識到我其實想問的問題。無論如何,我要在這裏發佈它,只要告訴別人認爲它有用。
__init__.py
{% extends %}
總是必須首先在模板中,所以它不可能使用{% load %}
加載此標記。相反,它必須以與django標籤相同的方式加載。
所以這需要去某個地方,迫使它立即運行。
# The `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')
程序my_app/templatetags/overriden_tags.py
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)
mixins.py
class PreventableExtendsMixin(object):
def __init__(self, **kwargs):
self.prevent_extends = kwargs.pop('prevent_extends')
super(PreventableExtendsMixin, self).__init__(**kwargs)
def get_context_data(self, **kwargs):
context = super(PreventableExtendsMixin, self).get_context_data(**kwargs)
context['prevent_extends'] = self.prevent_extends
return context
用法
from third_party_app import LoginView
class MyLoginView(PreventableExtendsMixin, LoginView):
def __init__(self, **kwargs):
kwargs['prevent_extends'] = 'base.html'
super(MyLoginView, self).__init__(**kwargs)