Skip to content

Instantly share code, notes, and snippets.

@chronossc
Created August 11, 2015 22:18
Show Gist options
  • Save chronossc/b569820c782838676eb7 to your computer and use it in GitHub Desktop.
Save chronossc/b569820c782838676eb7 to your computer and use it in GitHub Desktop.
Simple tag that return 'active' if given url is same that you are.
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def as_active_url(context, url, css_class='active'):
"""
Usage:
{% url 'foobar' as url %}
<li class="{% as_active_url url %}"><a href="{{ url }}">URL 1</a></li>
{% url 'foobar' as url %}
<li class="{% as_active_url url %}"><a href="{{ url }}">URL 2</a></li>
"""
request = context.get('request', None)
if not request:
raise template.TemplateSyntaxError(
"Request must be enabled in context for this tag work. "
"Check docs at https://docs.djangoproject.com/en/1.8/ref/templates/api/#subclassing-context-requestcontext."
)
if request.get_full_path() == url:
return css_class
else:
return ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment