Django along with bootstrap navbar - distiinguishing link to current page

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

[home][gallery][user]

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.

Answers


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>
        </ul>
</div>

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

Profiling WebMethods services?

service soa webmethods

What techniques are available to profile services running in WebMethods Integration Server?

Unable to debug WCF service message

visual-studio-2008 wcf

I've got a Visual Studio 2008 solution with a WCF service, and a client.