Expanding template variables in Django Flatpages

4 May 2010  •  Comments

Recently I had to make use of Django's Flatpages framework for a project.  Normally the flatpages framework is fine for a couple pages out of the box but I didn't like the idea of hard coding my media url in the flatpages when it was dynamic everywhere else.  I also wanted to be able to use other tags and filters in the flatpage and have Django render them as usual. 

I didn't want to re-write the flatpages framework (although it's a fairly easy task in Django), rather I wanted to just add one feature.  So how did I do it?  I created a string filter that takes the page content and re-renders it at a template level.  Here's the code:

Starting with the custom filter itself:

from django import template
from django.template import Template, Context
from django.template.defaultfilters import stringfilter
from django.conf import settings
register = template.Library()

@register.filter
@stringfilter
def parse_blocks(value):
    """ use the django template loader and response object to spit 
    out rendered content
    """
    t = Template(value)
    c = Context({ 'MEDIA_URL': settings.MEDIA_URL })
    return t.render(c)

Not the greatest name for the filter I know, but eventually I want it to recognize template blocks.  You can call it what you like. 

Next up the template itself:

{% extends 'base.html' %}
{% load parse_blocks %}

{% block title %}- {{ flatpage.title }}{% endblock %}

{% block content %}
{{ flatpage.content|parse_blocks }}
{% endblock %}

Again pretty self explanatory.  Pass the content as a string to the filter and let the filter do it's job.

A sample flatpage:

<div class="content">
    <img src="{{ MEDIA_URL }}images/image.png" /></div>

You really have to love the ability of Django to make these kind of hacks work without much effort.

Twitter Facebook Stumbleupon Reddit Digg

Copyright © 2004 - 2013 Nomad.Works | Made in Ottawa