Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSameer Zahid
5,967 PointsDjango - What's the best way to have an active class for a current page in a navigation menu?
Hello,
I've followed the Django Track up until "Django Class-based Views" while creating a website of my own. I have accomplished everything I needed for my website, except I can't figure out how to have an active class for a menu item if the user is at that page.
I've searched Google for this but all the solutions I got were not very DRY and failed in many cases.
What I have so far is this:
layout.html
<nav class="main-nav">
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>
</nav>
urls.py
url(r'^$', views.home, name='home'),
url(r'^about/', views.about, name='about'),
url(r'^contact/', views.contact, name='contact'),
So for instance, I'd like to apply a class of 'active' for the 'Home' link in layout.html, if the user is accessing the 'home' View.
Please let me know about this and thanks a lot!
1 Answer
Alx Ki
Python Web Development Techdegree Graduate 14,822 PointsHi, Sameer Zahid !
You can return some context back to the view using get_context_data() in your class view.
For example if you return context['activate'] = 'home'
Then according to that data, you may "activate" an <a></a> object:
<nav class="main-nav">
<a {% if activate == 'home' %}class="active"{% endif %} href="{% url 'home' %}">Home</a>
<a {% if activate == 'about' %}class="active"{% endif %} href="{% url 'about' %}">About</a>
<a {% if activate == 'contact' %}class="active"{% endif %} href="{% url 'contact' %}">Contact</a>
</nav>
Information about get_context_data() with examples is HERE
Does it help?