Created
November 18, 2014 23:35
-
-
Save whusterj/382399a7a496136c7c00 to your computer and use it in GitHub Desktop.
Django custom template tag useful for marking navigation links with an 'active' class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Easily mark navigation links with an 'active' class in Django templates. | |
Usage:: | |
<a href="{% url 'some_view_name' %}" class="{% active request 'some_view_name' %}">Link to Somewhere</a> | |
""" | |
from django.core.urlresolvers import reverse | |
from django import template | |
register = template.Library() | |
@register.simple_tag | |
def active(request, url_name): | |
"""Use when adding an 'active' class to navigation links""" | |
if request.path == reverse(url_name): | |
return 'active' | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage
This tag mirrors the syntax of the built-in
{% url %}
tag and likewise looks up the path for a given view name. It compares this path with the current request path. If they are equal, it returns an 'active' class.