Reputation: 1106
I have created a template tag for return active or nothing to every menu item, if I hardcode every url , it will work, like here:
<li class="{% active request '^/danmark/$' %}"><a href="/danmark/"> Hele Danmark</a>
But if i use dymanic url, there wont be add any active class to any menu item, if the the url is ^/danmark/{{a.area}}/$
, like here:
{% for a in all_areas %}
<li class="{% active request '^/danmark/{{a.area}}/$' %} "><a href= "/danmark/{{a.area}}/">{{a.area}} </a></li>
{% endfor %}
and template tag:
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 ''
What can I do here?
Upvotes: 1
Views: 3087
Reputation: 199
You can try this
{% with request.resolver_match.url_name as url_name %}
<ul id="menu">
<li class="{% if url_name == 'home' %}active{% endif %}">Home</li>
<li class="{% if url_name == 'about' %}active{% endif %}">About</li>
<li class="{% if url_name == 'employer' %}active{% endif %}">Employer</li>
</ul>
{% endwith %}
Where your urls are like
url(r'$','home_view', name='home'),
url(r'about/$','about_view', name='about'),
url(r'employer/$','employer_view', name='employer')
Upvotes: 6
Reputation: 6824
Why don't put some signal in your view like:
active = 'danmark'
then in temlate you can do:
<li{% if active=='danmark' %} class="active"{% endif %}><a href="/danmark/"> Hele Danmark</a></li>
Upvotes: 0