How to add class active
for html templates, eg: nav menus, bassed in generic.ListView
. This my problem that was asked in gitter of django https://gitter.im/django/django?at=569019e287cb99b53b8802e8, and this is my question of it:
somebody can help me how to add class
active
for html templates, eg: nav menus, bassed ingeneric.ListView
?
some idea i was try with{% if request.resolver_match.url_name == "name" %}
and{% if request.get_full_path == '/mypage/' %}
but it isn’t work.. i think may it becausepagination
ingeneric.ListView
…
any idea how to solved it?
Yup, thereis my problem because i work with generic.ListView
, (or similiar with view that ^use list view).
And was answered with nick pace-noge
there (https://gitter.im/django/django?at=5690326c5fd2ae3c32b48276), he assumming to use templatetags
. I never think it before.. and Thank you so much..
And thereis answer of it:
- in your
app/urls.py
url(r'^direktorat/$', DirektoratListView.as_view(), name="direktorat-list"),
- in your templatetags,
app/templatetags/active_nav.py
from django import template
register = template.Library()
@register.simple_tag
def active(request, pattern):
import re
if re.search(pattern, request.path):
return "active"
return ""
- in your templates
{% load active_nav %} # load the templatetags
{% url 'direktorat-list' as direktorat_list_url %} #save it as variable for future change
<!-- link -->
<li class="{% active request direktorat_list_url %}"><a href="{{ direktorat_list_url }}">Direktorat</a></li>
You can do it with some conditions like `{% if request.resolver_match.url_name == "name" %}` or `{% if request.get_full_path == '/mypage/' %}`, then for example like this:
{% load nav_menus_active_tags %}
{% url 'popular_videos_page' as popular_videos_page %}
<li class="{% if request.resolver_match.url_name == "popular_videos_page" %}{% active request popular_videos_page %}{% endif %}">
<a class="nav-popular" href="{% url 'popular_videos_page' %}"><span class="glyphicon glyphicon-signal" aria-hidden="true"></span> Popular</a>
</li>
May it usefully…