Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Highlight Navigation based on current page?

I am building a webapp that has several main sections. Each section has several sub-sections. I have a main_nav.html file that holds the nav for the main section. This is added to the based HTML file with the {% include ... %} command in the base.html template. Further, I have several sub-section nav files, each of which are added to any given page with the same {% include ... %} command.

All the nav bars are very simple, just text with <a href...> tags.

I want to highlight the link for the current main section and the current sub-section. Since this webapp is rather big, I was hoping to somehow do this without adding page-specific information. Plus, I want it to just "work" as the webapp expands to include more sections and sub-sections. For example, could this be done by looking at the actual URL in use? I was hoping to put this could within the nav files themselves and not have to load some variable or whatever within every django view.

So, for example, the nav looks like this:

(main ->)            [Systems][Invoices][Work Orders][Admin] (system sub-nav ->)  [Owner][Billing][Contacts] 

So if I am in the Billing section of Systems, I want the link Systems in bold and the link Billing to be bold (or some other simple highlight)

Or:

(main ->)                 [Systems][Invoices][Work Orders][Admin] (Work-Orders sub-nav ->)  [Create New][Outstanding] 

If I am in the Outstanding section of Work Orders, the link Work Orders and the link Outstanding needs to be highlighted.

Any ideas?

like image 338
Garfonzo Avatar asked Oct 05 '11 17:10

Garfonzo


1 Answers

Assuming you use render_to_response with RequestContext or use the render method or class-based views of Django 1.3, you'll have the request object available in your template. From there, it's a simple matter of just accessing the current path and comparing it with expected values:

<a href="/some/path/to/be/highlighted/"{% if request.path == '/some/path/to/be/highlighted/' %} class="active"{% endif %}>Some Link</a> 

In Django 1.3, I like to save redundancy and use the as operator for the URL lookup:

{% url 'some_urlpattern_name' as url %} <a href="{{ url }}"{% if request.path == url %} class="active"{% endif %}>Some Link</a> 

Repeat as necessary for each link.

like image 103
Chris Pratt Avatar answered Nov 04 '22 13:11

Chris Pratt