Login

Boxes as template tags

Author:
pedrolima
Posted:
February 20, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.