Created
August 11, 2015 22:18
-
-
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.
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
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