带有 if-then-else 选项的解决方案:
from django import template
from django.template.base import Node, NodeList, TemplateSyntaxError
register = template.Library()
class IfCurrentViewNode(Node):
child_nodelists = ('nodelist_true', 'nodelist_false')
def __init__(self, view_name, nodelist_true, nodelist_false):
self.view_name = view_name
self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
def __repr__(self):
return "<IfCurrentViewNode>"
def render(self, context):
view_name = self.view_name.resolve(context, True)
request = context['request']
if request.resolver_match.url_name == view_name:
return self.nodelist_true.render(context)
return self.nodelist_false.render(context)
def do_ifcurrentview(parser, token):
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one argument"
" (path to a view)" % bits[0])
view_name = parser.compile_filter(bits[1])
nodelist_true = parser.parse(('else', 'endifcurrentview'))
token = parser.next_token()
if token.contents == 'else':
nodelist_false = parser.parse(('endifcurrentview',))
parser.delete_first_token()
else:
nodelist_false = NodeList()
return IfCurrentViewNode(view_name, nodelist_true, nodelist_false)
@register.tag
def ifcurrentview(parser, token):
"""
Outputs the contents of the block if the current view match the argument.
Examples::
{% ifcurrentview 'path.to.some_view' %}
...
{% endifcurrentview %}
{% ifcurrentview 'path.to.some_view' %}
...
{% else %}
...
{% endifcurrentview %}
"""
return do_ifcurrentview(parser, token)