Login

Boxes as template tags

Author:
pedrolima
Posted:
February 20, 2008
Language:
Python
Version:
.96
Tags:
template-tag box
Score:
1 (after 1 ratings)

It's a template tag used to create boxes with nested divs (useful to keep the templates DRY). For example:

{% menubox titlevar %} Content here {% endmenubox %}

will generate the html with the nested divs

div class=box div class=box-outer div class=box-inner Headline Content /div /div /div

more detail on this blog post

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.template import Library, Node, TemplateSyntaxError

register = Library()

def do_menubox(parser, token):
    nodelist = parser.parse(('endmenubox',))
    parser.delete_first_token()
    try:
        tag_name, title = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%r tag requires exactly two arguments" % \
              token.contents.split()[0]
    return MenuboxNode(nodelist, parser.compile_filter(title))

class MenuboxNode(Node):
    
    def __init__(self, nodelist, title):
        self.nodelist = nodelist
        self.title = title
        
    def render(self, context):
        title = self.title.resolve(context)
        output = self.nodelist.render(context)
        return '''<div class="box"><div class="box-outer"><div class="box-inner"><h2>%s</h2>%s</div></div></div>''' % (title, output)

register.tag('menubox', do_menubox)

More like this

  1. Cleanup dirty HTML from a WYSIWYG editor by denis 5 years, 11 months ago
  2. "Zoom in" on rendered HTML that the test client returns by peterbe 6 years, 1 month ago
  3. Markdown and Syntax Highlighting in Django by blinks 8 years, 2 months ago
  4. really spaceless (trim spaces at line start) by wolfram 7 years, 4 months ago
  5. improved sortby template tag by gmandx 5 years, 10 months ago

Comments

Please login first before commenting.