Django along with bootstrap navbar - distiinguishing link to current page

I use bootstrap for my django project. I have a navbar like this:


How can I change the CSS properties of a specific navbar button to correspond to a currently opened page?

For example, if I am on the home page, the home button would be highlighted.


Solution 1

I usually have the navbar template gets included in all templates, each template should define what the page is this.

For example

# nav.html

<div class="..">
    <div class="..">My Nav</div>
        <ul class="..">
            <a href=".." class=".. {% if active == 'home' %} active {% endif %}">Home</a>
            <a href="/settings/" class="list-group-item {% if active == 'settings' %} active {% endif %}">Settings</a>

Then in each template you specify which should be active. something like this

# home.html 

{% include "yourtemplatedir/nav.html" with active='home' %}

# settings.html 

{% include "yourtemplatedir/nav.html" with active='settings' %}

Solution 2

Using context processor will make it sometimes easy

def get_current_path(request):
    return {
       'current_path': request.get_full_path()

In your template you can use {{ current_path }} to determine which nav item should be active.

You can also enhance the context processor code in order to check the prefix of the url and set the active_page variable automatically. so you don't need to set it with each include (In case you include the nav.html in your base always). However it really hard to have exceptions in here.

Need Your Help

DataVisualization - empty function bodies in ILSpy

c# winforms mschart

I'm doing some astrophysics research and I'm analysing data using Win-Form Chart component. On X-Axis is date and on Y-Axis is value, and I'm applying MovingAverage using member method

VTD-XML: how to execute XPath query not from the root element

java xml xpath vtd-xml

I need to handle large XML files, and I decided to move from DOM parser to VTD-XML.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.