Navigation in django

I've just done my first little webapp in django and I love it. I'm about to start on converting an old production PHP site into django and as part its template, there is a navigation bar.

In PHP, I check each nav option's URL against the current URL, in the template code and apply a CSS class if they line up. It's horrendously messy.

Is there something better for django or a good way of handling the code in the template?

To start, how would I go about getting the current URL?


ANSWERS:


I use template inheritance to customize navigation. For example:

base.html

<html>
    <head>...<head>
    <body>
        ...
        {% block nav %}
        <ul id="nav">
            <li>{% block nav- %}<a href="">Home<a>{% endblock %}<li>
            <li>{% block nav-about %}<a href="">About<a>{% endblock %}<li>
            <li>{% block nav- %}<a href="">Contact<a>{% endblock %}<li>
        <ul>
        {% endblock %}
        ...
    <body>
<html>

about.html

{% extends "base.html" %}

{% block nav-about %}<strong class="nav-active">About<strong>{% endblock %}
    

You do not need an if to do that, have a look at the following code:

tags.py

@register.simple_tag
def active(request, pattern):
    import re
    if re.search(pattern, request.path):
        return 'active'
    return ''

urls.py

urlpatterns += patterns('',
    (r'$', view__method, '_url_name'),
    (r'$', view__method, '_url_name'),
    (r'$', view__method, '_url_name'),
)

base.html

{% load tags %}

'_url_name' as  %}
'_url_name' as  %}
'_url_name' as  %}

<div id="navigation">
    <a class="{% active request  %}" href="">Home<a>
    <a class="{% active request  %}" href="">Services<a>
    <a class="{% active request  %}" href="">Contact<a>
<div>

that's it. for implementation details have a look at:
gnuvince.wordpress.com
110j.wordpress.com


I've seen jpwatts', 110j's, nivhab's & Marcus Whybrow's answers, but they all seem to lack in something: what about the root path ? Why it's always active ?

So I've made an other way, easier, which make the "controller" decides by itself and I think it resolve most of the big problems.

Here is my custom tag:

 myapp_tags.py

@register.simple_tag
def nav_css_class(page_class):
    if not page_class:
        return ""
    else:
        return page_class

Then, the "controller" declares CSS classes needed (in fact, the most important is it declares its presence to the template)

 views.py

def ping(request):
    context={}
    context["nav_ping"] = "active"
    return render(request, 'myappping.html',context)

And finally, I render it in my navigation bar:

<!-- sidebar.html -->

{% load myapp_tags %}
...

<a class="{% nav_css_class nav_ %}" href="">
    Accueil
<a>
<a class="{% nav_css_class nav_candidats %}" href="">
    Candidats
<a>
<a class="{% nav_css_class nav_ping %}" href="">
    Ping
<a>
<a class="{% nav_css_class nav_stat %}" href="">
    Statistiques
<a>
...

So each page has its own nav_css_class value to set, and if it's set, the template renders active: no need of request in template context, no URL parcing and no more problems about multi-URL pages or root page.


I liked the cleanness of 110j above so I took most of it and refactored to solve the 3 problems I had with it:

  1. the regular expression was matching the '' url against all others
  2. I needed multiple URLs mapped to one navigation tab, so I needed a more complex tag that takes variable amount of parameters
  3. fixed some url problems
    1. Here it is:

       tags.py
      from django import template
      
      register = template.Library()
      
      @register.tag
      def active(parser, token):
          args = token.split_contents()
          template_tag = args[0]
          if len(args) < 2:
              raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
          return NavSelectedNode(args[1:])
      
      class NavSelectedNode(template.Node):
          def __init__(self, patterns):
              self.patterns = patterns
          def render(self, context):
              path = context['request'].path
              for p in self.patterns:
                  pValue = template.Variable(p).resolve(context)
                  if path == pValue:
                      return "active"  change this if needed for other bootstrap version (compatible with 3.2)
              return ""
      
       urls.py
      urlpatterns += patterns('',
          url(r'$', view__method, {}, name='_url_name'),
          url(r'$', view__method, {}, name='_url_name'),
          url(r'$', view__method, {}, name='_url_name'),
          url(r'$', view_2_method, {}, name='2_url_name'),
      )
      
       base.html
      
      {% load tags %}
      
      _url_name as  %}
      _url_name as  %}
      _url_name as  %}
      2_url_name as 2 %}
      
      <div id="navigation">
          <a class="{% active request  %}" href="">Home<a>
          <a class="{% active request  %}" href="">Services<a>
          <a class="{% active request  2 %}" href="">Contact<a>
      <div>
      
          

      A little enhancement over @tback's answer, without any %if% tags:

       navigation.py
      from django import template
      from django.core.urlresolvers import resolve
      
      register = template.Library()
      
      @register.filter(name="activate_if_active", is_safe=True)
      def activate_if_active(request, urlname):
        if resolve(request.get_full_path()).url_name == urlname:
          return "active"
        return ''
      
      
      

      Use it in your template like that:

      {% load navigation %}
      <li class="{{ request|activate_if_active:'url_name' }}">
        <a href="">My View<a>
      <li>
      
      
      

      And include "django.core.context_processors.request" in your TEMPLATE_CONTEXT_PROCESSORS setting.


      Mine is a bit similar to another JS approach submitted previously.. just without jQuery...

      Say we have in base.html the following:

      <div class="pure-u-1 pure-menu pure-menu-open pure-menu-horizontal header" >
          <ul class="">
              <li id=""><a href="">Home<a><li>
              <li id="news"><a href="">News<a><li>
              <li id="analysis"><a href="">Analysis<a><li>
              <li id="opinion"><a href="">Opinion<a><li>
              <li id="data"><a href="">Data<a><li>
              <li id="events"><a href="">Events<a><li>
              <li id="forum"><a href="">Forum<a><li>
              <li id="subscribe"><a href="">Subscribe<a><li>
          <ul>
          <script type="textjavascript">
              (function(){
                  loc=\w+.exec(window.location.pathname)[0];
                  el=document.getElementById(loc).className='pure-menu-selected';         
              })();   
          <script>
      <div>
      
      
      

      I just made my hierarchy to follow a certain URL pattern... after the host address... i have my main category, eg, , news, analysis, etc. and the regex just pulls the first word out of the location


      I use a combination of this mixin for class based views:

      class SetActiveViewMixin(object):
          def get_context_data(self, **kwargs):
              context = super(SetActiveViewMixin, self).get_context_data(**kwargs)
              context['active_nav_menu'] = {
                  self.request.resolver_match.view_name: ' class="pure-menu-selected"'
              }
              return context
      
      
      

      with this in the template:

      <ul>
          <li{{active_nav_menu.node_explorer }}><a href="">Explore<a><li>
          <li{{active_nav_menu.node_create }}><a href="">Create<a><li>
          <li{{active_nav_menu.node_edit }}><a href="">Edit<a><li>
          <li{{active_nav_menu.node_delete }}><a href="">Delete<a><li>
      <ul>
      
          

      I used jquery to highlight my navbars. This solution simply adds the css class "active" to the item which fits the css selector.

      <script type="textjavascript" src=""><script>
      <script>
          $(document).ready(function(){
              var path = location.pathname;
              $('ul.navbar a.nav[href$="' + path + '"]').addClass("active");
          });
      <script>
      
          

      I also used jQuery to highlight it and find it more elegant than cluttering the template with non-semantic Django template tags.

      The code below works with nested dropdowns in bootstrap 3 (highlights both the parent, and the child <li> element.

       DOM Ready
      $(function() {
           Highlight current page in nav bar
          $('.nav, .navbar-nav li').each(function() {
               Count the number of links to the current page in the <li>
              var matched_links = $(this).find('a[href]').filter(function() {
                  return $(this).attr('href') == window.location.pathname; 
              }).length;
               If there's at least one, mark the <li> as active
              if (matched_links)
                  $(this).addClass('active');
          });
      });
      
      
      

      It's also quite easy to add a click event to return false (or change the href attribute to ) for the current page, without changing the templatehtml markup:

              var matched_links = $(this).find('a[href]').filter(function() {
                  var matched = $(this).attr('href') == window.location.pathname;
                  if (matched)
                      $(this).click(function() { return false; });
                  return matched;
              }).length;
      
          

      I know I'm late to the party. I didn't like any of the popular solutions though:

      The block method seems wrong: I think the navigation should be self contained.

      The template_tag method seems wrong: I don't like that I have to get the url from the url-tag first. Also, I think the css-class should be defined in the template, not the tag.

      I therefore wrote a filter that doesn't have the drawbacks I described above. It returns True if a url is active and can therefore be used with {% if %}:

      {% load navigation %}
      <li{% if request|active:"" %} class="active"{% endif %}><a href=""" %}">Home<a><li>
      
      
      

      The code:

      @register.filter(name="active")
      def active(request, url_name):
          return resolve(request.path_info).url_name == url_name
      
      
      

      Just make sure to use RequestContext on pages with navigation or to enable the request context_processor in your settings.py

      TEMPLATE_CONTEXT_PROCESSORS = (
          ...
          'django.core.context_processors.request',
      )
      
          

      from this SO Question

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

      Repeat as necessary for each link.


      Since Django 1.5:

      In all generic class-based views (or any class-based view inheriting from ContextMixin), the context dictionary contains a view variable that points to the View instance.

      So if you are using such views, you could add something likie breadcrumbs as a class level field and use it in your templates.

      Example view code:

      class YourDetailView(DetailView):
           breadcrumbs = ['detail']
           (...)
      
      
      

      In your template you could use it in this way:

      <a href="" {% if 'detail' in view.breadcrumbs %}class="active"{% endif %}>Detail<a>
      
      
      

      If you want to additionally "highlight" parent navigation items, you need to extend breadcrumbs list:

      class YourDetailView(DetailView):
           breadcrumbs = ['dashboard', 'list', 'detail']
           (...)
      
      
      

      ... and in your template:

      <a href="" {% if 'dashboard' in view.breadcrumbs %}class="active"{% endif %}>Dashboard<a>
      <a href="" {% if 'list' in view.breadcrumbs %}class="active"{% endif %}>List<a>
      <a href="" {% if 'detail' in view.breadcrumbs %}class="active"{% endif %}>Detail<a>
      
      
      

      This is easy and clean solution and works pretty well with nested navigation.


      I took the code from nivhab above and removed some wierdness and made it into a clean templatetag, modified it so that accountedit will still make account tab active.

      current_nav.py
      from django import template
      
      register = template.Library()
      
      @register.tag
      def current_nav(parser, token):
          import re
          args = token.split_contents()
          template_tag = args[0]
          if len(args) < 2:
              raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
          return NavSelectedNode(args[1])
      
      class NavSelectedNode(template.Node):
          def __init__(self, url):
              self.url = url
      
          def render(self, context):
              path = context['request'].path
              pValue = template.Variable(self.url).resolve(context)
              if (pValue == '' or pValue == '') and not (path  == '' or path == ''):
                  return ""
              if path.startswith(pValue):
                  return ' class="current"'
              return ""
      
      
      
      template.html
      {% block nav %}
      {% load current_nav %}
       as _url %}
      signup as signup_url %}
      auth_login as auth_login_url %}
      <ul class="container">
          <li><a href=""{% current_nav _url %} title="Home">Home<a><li>
          <li><a href=""{% current_nav auth_login_url %} title="Login">Login<a><li>
          <li><a href=""{% current_nav signup_url %} title="Signup">Signup<a><li>
      <ul>
      {% endblock %}
      
          

      I'm the author of django-lineage which I wrote specifically to solve this question :D

      I became annoyed using the (perfectly acceptable) jpwatts method in my own projects and drew inspiration from 110j's answer. Lineage looks like this:

      {% load lineage %}
      <div id="navigation">
          <a class="{% ancestor '' %}" href="">Home<a>
          <a class="{% ancestor '' %}" href="">Services<a>
          <a class="{% ancestor '' %}" href="">Contact<a>
      <div>
      
      
      

      ancestor is simply replaced with "active" if the argument matches the start of current page URL.

      Variable arguments, and full %} type reverse resolution, is also supported. I sprinkled in a few configuration options and fleshed it out a little and packaged it up for everyone to use.

      If anyone is interested, read a bit more about it at:

      >> github.commarcuswhybrowdjango-lineage


      here is pretty simple solution,


      Create an include template "intranetnav_item.html":

      {% load url from future %}
      
      view as view_url %}
      <li class="nav-item{% ifequal view_url request.path %} current{% endifequal %}">
          <a href="">{{ title }}<a>
      <li>
      
      
      

      And include it in the nav element:

      <ul>
          {% include "intranetnav_item.html" with view='intranet.views.' title='Home' %}
          {% include "intranetnav_item.html" with view='crm.views.clients' title='Clients' %}
      <ul>
      
      
      

      And you need to add this to settings:

      from django.conf import global_settings
      TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
          'django.core.context_processors.request',
      )
      
          

      Slightly modifying Andreas' answer, it looks like you can pass in the name of the route from urls.py to the template tag. In my example my_tasks, and then in the template tag function use the reverse function to work out what the URL should be, then you can match that against the URL in the request object (available in the template context)

      from django import template
      from django.core.urlresolvers import reverse
      
      register = template.Library()
      
      @register.tag
      def active(parser, token):
          args = token.split_contents()
          template_tag = args[0]
          if len(args) < 2:
              raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
          return NavSelectedNode(args[1:])
      
      class NavSelectedNode(template.Node):
          def __init__(self, name):
              self.name = name
      
          def render(self, context):
      
              if context['request'].path == reverse(self.name[1]):
                  return 'active'
              else:
                  return ''
      
      
      

      urls.py

      url(r'^tasksmy', my_tasks, name = 'my_tasks' ),
      
      
      

      template.html

      <li class="{% active request all_tasks %}"><a href="">Everyone<a><li>
      
          

      Here's my go at it. I ended up implementing a class in my views that contains my navigation structure (flat with some metadata). I then inject this to the template and render it out.

      My solution deals with i18n. It probably should be abstracted out a bit more but I haven't really bothered with that really.

      views.py:

      from django.utils.translation import get_language, ugettext as _
      
      
      class Navi(list):
          items = (_('Events'), _('Users'), )
      
          def __init__(self, cur_path):
              lang = get_language()
              first_part = '' + cur_path.lstrip('').split('')[0]
      
              def set_status(n):
                  if n['url'] == first_part:
                      n['status'] == 'active'
      
              for i in self.items:
                  o = {'name': i, 'url': '' + slugify(i)}
                  set_status(o)
                  self.append(o)
      
       remember to attach Navi() to your template context!
       ie. 'navi': Navi(request.path)
      
      
      

      I defined the template logic using includes like this. Base template:

      {% include "includesnavigation.html" with items=navi %}
      
      
      

      Actual include (includesnavigation.html):

       <ul class="nav">
           {% for item in items %}
               <li class="{{ item.status }}">
                   <a href="">{{ item.name }}<a>
               <li>
           {% endfor %}
       <ul>
      
      
      

      Hopefully someone will find this useful! I guess it would be pretty easy to extend that idea to support nested hierarchies etc.


      Just another ehnancement of the original solution.

      This accept multiple patterns and which is best also unnamed patterns written as relative URL wrapped in '"', like following:

      admin:clients_client_changelist as clients %}
      admin:clients_town_changelist as towns %}
      admin:clients_district_changelist as districts %}
      
      <li class="{% active "" %}"><a href="">Home<a><li>
      <li class="{% active clients %}"><a href="">Clients<a><li>
      {% if request.user.is_superuser %}
      <li class="{% active towns districts %}">
          <a href="">Settings<a>
          <ul>
              <li><a href="">Towns<a><li>
              <li><a href="">Districts<a><li>
          <ul>
      <li>
      {% endif %}
      
      
      

      Tag goes like this:

      from django import template
      
      register = template.Library()
      
      @register.tag
      def active(parser, token):
          args = token.split_contents()
          template_tag = args[0]
          if len(args) < 2:
              raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
          return NavSelectedNode(args[1:])
      
      class NavSelectedNode(template.Node):
          def __init__(self, urls):
              self.urls = urls
      
          def render(self, context):
              path = context['request'].path
      
              for url in self.urls:
                  if '"' not in url:
                      cpath = template.Variable(url).resolve(context)
                  else:
                      cpath = url.strip('"')
      
                  if (cpath == '' or cpath == '') and not (path == '' or path == ''):
                      return ""
                  if path.startswith(cpath):
                      return 'active'
              return ""
      
          

      This is just a variant of the css solution proposed by Toba above:

      Include the following in your base template:

      <body id="section-{% block section %}{% endblock %}">
      
      
      

      Then in your templates that extend the base use:

      {% block section %}show{% endblock %}
      
      
      

      You can then use css to highlight the current area based on the body tag (for example if we have a link with an id of nav-):

      section- anav-{
       font-weight:bold;
      }
      
          

      I just wanted to share my minor enhancement to nivhab's post. In my application I have subnavigations and I did not want to hide them using just CSS, so I needed some sort of "if" tag to display the subnavigation for an item or not.

      from django import template
      register = template.Library()
      
      @register.tag
      def ifnaviactive(parser, token):
          nodelist = parser.parse(('endifnaviactive',))
          parser.delete_first_token()
      
          import re
          args = token.split_contents()
          template_tag = args[0]
          if len(args) < 2:
              raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
          return NavSelectedNode(args[1:], nodelist)
      
      class NavSelectedNode(template.Node):
          def __init__(self, patterns, nodelist):
              self.patterns = patterns
              self.nodelist = nodelist
      
          def render(self, context):
              path = context['request'].path
              for p in self.patterns:
                  pValue = template.Variable(p).resolve(context)
                  if path == pValue:
                      return self.nodelist.render(context)
              return ""
      
      
      

      You can use this basically in the same way as the active tag:

      product_url as product %}
      
      {% ifnaviactive request product %}
          <ul class="subnavi">
              <li>Subnavi item for product 1<li>
              ...
          <ul>
      {% endifnaviactive %}
      
          

      My solution was to write a simple context processor to set a variable based on the request path:

      def navigation(request):
      """
      Custom context processor to set the navigation menu pointer.
      """
      nav_pointer = ''
      if request.path == '':
          nav_pointer = 'main'
      elif request.path.startswith(''):
          nav_pointer = ''
      elif request.path.startswith('other_stuff'):
          nav_pointer = 'other_stuff'
      return {'nav_pointer': nav_pointer}
      
      
      

      (Don't forget to add your custom processor to TEMPLATE_CONTEXT_PROCESSORS in settings.py.)

      Then in the base template I use an ifequal tag per link to determine whether to append the "active" class. Granted this approach is strictly limited to the flexibility of your path structure, but it works for my relatively modest deployment.


      I have multiple menus on the same page that are created dynamically through a loop. The posts above relating to the context gave me a quick fix. Hope this helps somebody. (I use this in addition to the active template tag - my fix solves the dynamic issue). It seems like a silly comparison, but it works. I chose to name the variables active_something-unique and something-unique, this way it works with nested menus.

      Here is a portion of the view (enough to understand what i am doing):

      def project_list(request, catslug):
          "render the category detail page"
          category = get_object_or_404(Category, slug=catslug, site__id__exact=settings.SITE_ID)
          context = {
              'active_category': 
                  category,
              'category': 
                  category,
              'category_list': 
                  Category.objects.filter(site__id__exact=settings.SITE_ID),
      
          }
      
      
      

      And this is from the template:

      <ul>
        {% for category in category_list %}
          <li class="tab{% ifequal active_category category %}-active{% endifequal %}">
            <a href="">{{ category.cat }}<a>
          <li>
        {% endfor %}
      <ul>
      
          

      Thanks for your answers so far, gents. I've gone for something slightly different again..

      In my template:

      <li{{ link1_active }}>...link...<li>
      <li{{ link2_active }}>...link...<li>
      <li{{ link3_active }}>...link...<li>
      <li{{ link4_active }}>...link...<li>
      
      
      

      Once I've worked out which page I'm on in the logic (usually in urls.py), I pass class="selected" as part of the context under the right name to the template.

      Eg if I'm on the link1 page, I'll append {'link1_active':' class="selected"'} to the context for the template to scoop up and inject.

      It appears to work and it's fairly clean.

      Edit: to keep HTML out of my controllerview, I've modified this a bit:

      <li{% if link1_active %} class="selected"{% endif %}>...link...<li>
      <li{% if link2_active %} class="selected"{% endif %}>...link...<li>
      ...
      
      
      

      It makes the template a little less readable, but I agree, it's better to not push through raw HTML from the urls file.


      I do it like this:

      <a class="tab {% ifequal active_tab "statistics" %}active{% endifequal %}" href="">Statistics<a>
      
      
      

      and then all I have to do is in my view add {'active_tab': 'statistics'} to my context dictionary.

      If you are using RequestContext you can get current path in your template as:

      {{ request.path }}
      
      
      

      And in your view:

      from django.template import RequestContext
      
      def my_view(request):
           do something awesome here
          return template.render(RequestContext(request, context_dict))
      
          

      You could apply a class or id to the body element of the page, rather than to a specific nav item.

      HTML:

      <body class="{{ nav_class }}">
      
      
      

      CSS:

      body. nav_,
      body.about nav_about { * Current nav styles * }
      
          

      You could use the reverse function with the appropriate parameters to get the current url.


       MORE:


       ? Navigation in django
       ? Navigation in django
       ? Django - Highlight Navigation based on current page?
       ? Why on earth do I have to pass RequestContext in all of my responses?
       ? jQuery: Adding class to the li element after the link is clicked, and deselecting all other classes
       ? Django -- Break up a request.path into each word?
       ? Django template: use of multiple block tags in same base
       ? Highlight Active Navigation: django 1.4.2
       ? Highlight dropdown menu in django
       ? django Navigation, need help on where to put the tags.py file