Skip to content

Instantly share code, notes, and snippets.

@niilante
Forked from RoboAndie/active_nav_tag.py
Created July 19, 2021 15:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niilante/7a96a459cbb08baefd5737fa0abe1da4 to your computer and use it in GitHub Desktop.
Save niilante/7a96a459cbb08baefd5737fa0abe1da4 to your computer and use it in GitHub Desktop.
Django template tag to highlight the active navigation item
@register.simple_tag(takes_context=True)
def active_nav(context, pattern_or_urlname, is_sr_text=False):
path = context['request'].path
if ',' in pattern_or_urlname:
patterns_to_try = pattern_or_urlname.split(',')
else:
patterns_to_try = [pattern_or_urlname]
for pattern in patterns_to_try:
try:
p = '^' + reverse(pattern)
except NoReverseMatch:
p = pattern
if re.search(p, path):
if is_sr_text:
return mark_safe(' <span class="sr-only">(current)</span>')
else:
return ' active'
return ''
# Based on this Stack Overflow answer: https://stackoverflow.com/a/18772289
# Designed for use with Bootstrap, use this template tag in your primary navigation menu
# to indicate to the user which navigation item is currently selected.
#
# Usage: Call this tag along with the name of the url pattern or the url or url fragment
# for the item path of the navigation item. To check multiple urls pass in a comma-separated
# list of patterns or urls.
#
# Returns: By default, this will return ' active' if the requested url is in the requested url.
# Use this as a CSS class on your navigation item to visually highlight the navigation item.
# Pass in `True` for is_sr_text to instead return ' <span class="sr-text">(current)</span>' to
# use in the text of the navigation item to alert screen readers that the navigation item is
# selected.
#
# Examples:
# <ul class="navbar-nav mr-auto">
# <li class="nav-item{% active_nav 'main:about' %}">
# <a class="nav-link" href="{% url 'main:about' %}">About{% active_nav 'main:about' True %}</a>
# </li>
# <li class="nav-item{% active_nav 'main:contact' %}">
# <a class="nav-link" href="{% url 'main:contact' %}">About{% active_nav 'main:contact' True %}</a>
# </li>
# <li class="nav-item dropdown{% active_nav 'users,organizations' %}">
# <a class="nav-link dropdown-toggle" href="#" id="myProfileButton" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
# Hi {{ user.get_short_name }}{% active_nav 'users,organizations' True %}
# </a>
# <div class="dropdown-menu" aria-labelledby="myProfileButton">
# <!-- ... -->
# </div>
# </li>
# </ul>
#
# Limitations: Currently this does a search only to see if the request path contains the url
# pattern, instead of checking for an exact match, which may result in false positives.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment