public
Last active

Template tag to check to check is a particular URL is active

  • Download Gist
templatetags.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
class NavSelectedNode(template.Node):
def __init__(self, obj, var):
self.obj = obj
self.var = var
def render(self, context):
value = template.Variable(self.obj).resolve(context)
context[self.var] = False
path = context['request'].path
# Here we can do some more complicated parsing of the current URL against our passed URL
if (path.startswith(value)) or (value == path):
context[self.var] = True
return ""
@register.tag
def is_active(parser, token):
"""Check if the provided string pattern is the current url"""
args = token.split_contents()
template_tag = args[0]
if len(args) != 4:
raise template.TemplateSyntaxError, "%r tag should be in the form {%% is_active [obj] as [variable] %%}" % template_tag
return NavSelectedNode(args[1], args[3])
 
# {% url someview as an_url %}
# {% is_active an_url as is_home_page %}
# {% if is_home_page %}...{% endif %}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.