What about the custom tag that you use to create your navigation item?
Below is the name of the URL for which the navigation item should be created, and the text that it should display. It generates a li tag with the class "selected" if the named URL matches the current URL (requires 'django.core.context_processors.request' in your TEMPLATE_CONTEXT_PROCESSORS ). Inside li, it generates a tag with a URL outline specified by url_name . It has the contents indicated by contents .
Obviously, this can be modified to create different layouts for the navigation item, if required.
The rest can be done using CSS.
Benefits:
Disadvantages:
Requires 'django.core.context_processors.request'
Required URLs, for example. urlpatterns = patterns('django.views.generic.simple', ... (r'^$', 'direct_to_template', {'template': 'index.html'}, 'index'), ... ) . This can be done differently (e.g. pass a url).
It does not cope with pages that are not exactly equal to the specified one, and therefore will not apply the selected class to whether it is on the page below in the hierarchical URL hierarchy. For example, if I am in / products /, it will highlight the nav element pointing to / products /. If I included / products / myProduct /, it will not highlight / products / link. It can be encoded, but it forces people to use reasonable URLs. For example, change the destination of additionalAttrs to additionalAttrs = ' class=selected' if (context['request'].path.startswith(path) and path != '/') or (context['request'].path == path) else '' .
code:
from django import template from django.core.urlresolvers import reverse register = template.Library() class NavNode(template.Node): def __init__(self, url_name, contents): self.url_name = url_name self.contents = contents def render(self, context): path = reverse(self.url_name) additionalAttrs = ' class=selected' if path == context['request'].path else '' return '<li'+additionalAttrs+'><a href="'+path+'">'+self.contents+'</a></li>' @register.tag def nav_link(parser, token): bits = token.split_contents() if len(bits) == 3: contents = bits.pop() url_name = bits.pop() else: raise template.TemplateSyntaxError, "%r tag requires a single argument" % bits[0] if contents[0] == contents[-1] and contents[0] in ('"', "'"): contents = contents[1:-1] return NavNode(url_name, contents)
source share