Skip to content

Instantly share code, notes, and snippets.

@imankulov
Created April 30, 2012 08:09
Show Gist options
  • Save imankulov/2556438 to your computer and use it in GitHub Desktop.
Save imankulov/2556438 to your computer and use it in GitHub Desktop.
Simple django templatetag for menu items
# -*- coding: utf-8 -*-
"""
Templatetag to be used in Django templates along with Twitter bootstrap CSS
library.
To make it work you must make sure that settings.py file contains a line like
this:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.request'
)
And then add to your template:
<div class="navbar">
<div class="navbar-inner">
<div class="container">
<ul class="nav">
{% menuitem "/foo/" "Foo Item" %}
{% menuitem "/bar/" "Bar Item" %}
</ul>
</div>
</div>
</div>
"""
from django import template
from django.utils.html import conditional_escape as esc
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def menuitem(context, url, title):
request = context['request']
class_attr = ''
print request.path, url, request.path == url
if request.path == url:
class_attr = ' class="active"'
template = u'<li{class_attr}><a href="{url}">{title}</a></li>'
return mark_safe(template.format(url=esc(url), title=esc(title), class_attr=class_attr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment