Skip to content

Instantly share code, notes, and snippets.

@Kmaschta
Last active February 20, 2016 17:23
Show Gist options
  • Save Kmaschta/b42f9ce2849fc4e15aa7 to your computer and use it in GitHub Desktop.
Save Kmaschta/b42f9ce2849fc4e15aa7 to your computer and use it in GitHub Desktop.
Django active view tag
from django import template
register = template.Library()
# custom tag "active_view" to return 'active' in the template when the view is active
# usage : {% active_view request name='view-name' %}
# usage : {% active_view request url='/view/abs/url' %}
# usage : {% active_view request re='^/view/ur.*' %}
@register.simple_tag(takes_context=True)
def active_view(context, name=None, url=None, re=None, cond=True):
request = context.request
if name is not None:
return 'active' if request.resolver_match.url_name == name and cond else ''
elif url is not None:
return 'active' if request.path_info == url and cond else ''
elif re is not None:
import re as _
return 'active' if _.search(re, request.path_info) and cond else ''
return ''
@Kmaschta
Copy link
Author

Credits to @waam

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment