Skip to content

Instantly share code, notes, and snippets.

@treejamie
Created June 14, 2013 09:18
Show Gist options
  • Save treejamie/5780583 to your computer and use it in GitHub Desktop.
Save treejamie/5780583 to your computer and use it in GitHub Desktop.
navigation example for a templatetag
from django.template import Node, Library, Variable
from myapp.models import Whatever
register = Library()
class NavigationNode(Node):
def __init__(self, user, varname):
# this is a variable in the template so we need to resolve later
self.user = Variable(user)
self.varname = varname
def render(self, context):
# resolve that user
user = self.user.resolve(context)
# get the nav bits
whatevers = Whatever.objects.filter(user=user)
# set it in the context
context[self.varname] = whatevers
# Nodes need to return a blank string
return ''
@register.filter
def get_nav_for_user(parser, token):
"""
split the token.cotents up into a list
get_nav_for_user request.user as nav
will become
['get_nav_for_user', 'request.user' 'as' 'nav']
"""
bits = token.contents.split()
# now return the node using bits[1] - request.user
# and bits[3] - nav
return NavigationNode(bits[1], bits[3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment