Skip to content

Instantly share code, notes, and snippets.

@gavinwahl
Created September 28, 2011 19:34
Show Gist options
  • Save gavinwahl/1248989 to your computer and use it in GitHub Desktop.
Save gavinwahl/1248989 to your computer and use it in GitHub Desktop.
tmb and div nodes
from django import template
register = template.Library()
class ParseClassesNode(template.Node):
def parse_until(self, parser, token, end):
contents = token.split_contents()
self.classes = ' '.join(contents[1:])
self.nodelist = parser.parse((end,))
parser.delete_first_token()
class TmbNode(ParseClassesNode):
def __init__(self, parser, token):
self.parse_until(parser, token, 'endtmb')
def render(self, context):
top_contents = []
bottom_contents = []
middle_contents = []
for node in self.nodelist:
if isinstance(node, DivNode) and node.classes == 'top':
top_contents.append(node.render(context))
elif isinstance(node, DivNode) and node.classes == 'bottom':
bottom_contents.append(node.render(context))
else:
middle_contents.append(node.render(context))
if not top_contents:
top_contents = ['<div class="top"/>']
if not bottom_contents:
bottom_contents = ['<div class="bottom"/>']
return '<div class="%s">%s</div>' % (self.classes, ''.join(top_contents + middle_contents + bottom_contents))
class DivNode(ParseClassesNode):
def __init__(self, parser, token):
self.parse_until(parser, token, 'enddiv')
def render(self, context):
contents = self.nodelist.render(context)
return '<div class="%s">%s</div>' % (self.classes, contents)
register.tag('tmb', TmbNode)
register.tag('div', DivNode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment