Wednesday 9 May 2012

A Minimal Markdown Template Tag for Django

Sometimes I find myself needing to put blocks of static content into a HTML document and I find it painful to have to manually type out the tags. It’s a waste of precious time and Django doesn’t provide a tag to accompany the markdown template filter

Here’s the code in full copy and paste glory.

 import markdown from django import template  register = template.Library()  class MarkDownNode(template.Node):          def __init__(self, nodelist):         self.nodelist = nodelist          def render(self, context):         return markdown.markdown(self.nodelist.render(context))   @register.tag('markdown') def markdown_tag(parser, token):     """     Enables a block of markdown text to be used in a template.      Syntax::              {% markdown %}             ## Markdown                          Now you can write markdown in your templates. This is good because:                          * markdown is awesome             * markdown is less verbose than writing html by hand                          {% endmarkdown %}     """     nodelist = parser.parse(('endmarkdown',))     # need to do this otherwise we get big fail     parser.delete_first_token()     return MarkDownNode(nodelist) 

My tag does the job, but If you’re looking for something a little more fully featured then you should look at django-markdown-deux.