26
Sep
07

Boxes as template tags

With CSS it's very simple to do the markup of a square box. But to make those popular boxes with round corners most approaches use nested divs. For a flexible size box the following markup is typical:

<div class="box">
  <div class="box-outer">
    <div class="box-inner">
      <h2>Headline</h2>
      <p>Content</p>
    </div>
  </div>
</div>

It's a bad idea to repeat this code all over the templates. So a template tag can be a good option. The kind of template that would be interesting to have is one that outputs the boilerplate divs given the headline and the content. Something like:

{% menubox "Box title here" %}
    <p>Content here</p>
{% endmenubox %}

Django makes the writing of this tag very easy and the documentation is very clear. Bellow is the result for such tag.

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)

Update: The tag now also works with variable names in the title. The following would output the value of titlevar as the title of the box

{% menubox titlevar %}
    <p>Content here</p>
{% endmenubox %}



4 Responses to “Boxes as template tags”


  1. 1 September 28, 2007 at 02:58 pm by dp_wiz

    Title really should not be restricted to quoted strings. You'd better add some variable-resolving code.

  2. 2 September 29, 2007 at 12:44 pm by pedro

    Fair point. I've updated the code to add variable-resolving. Thanks for your feedback.

  3. 3 October 04, 2007 at 04:25 pm by quentinsf

    Nice - neat - used it - thanks!

  4. 4 May 03, 2008 at 07:44 am by macdet

    @Nice - neat - used it - thanks!

    YES, your articles open my eyes :) Espero que yo entiendo algo!

    I try to include algo under http://wwww.mobbing-gegner.de

Leave a Reply