Sunday, August 23, 2009

Accessing Django Template filters in Google App Engine

This is a quick one. Django templates (including the version 0.96 supported for the Google App Engine Webapp framework) have this notion of output filters. Within any Django template you can output one of the variables passed to the rendering command using a simple markup within your HTML. This example:

<p>{{myvar}}</p>

outputs the variable myvar. One of the great inclusions in the templating language is filters. Filters are a range of formatting and transformation routines built into the templating language. This means you can format dates, truncate data, strip or escape HTML tags, replace linefeeds with paragraph tags and more within your template, not your calling code, which keeps your controller and model focused on their role and not overly processing data for the view. This makes your code cleaner. Filters can also be chained together to combine effects. For example:

<p>{{myvar|striptags|truncatewords:"10"}}</p>


This code removes html tags for the myvar variable and then truncates the result to 10 complete words. All of this goodness is available within the Webapp framework provided with Google App Engine. Read the documentation of the 0.96 version of Django Templates (used in App Engine).

Segregating the data transformation for view logic into the view is mostly very useful and powerful, but sometimes you need the functionality in filters outside of a template. For example the slugify filter creates a URL-safe string. Using slugify within the template is easy, but what happens when you need to redirect to the slugified URL? You could replicate the functionality outside of the template, but as well as duplicating code you are introducing the possibility that your algorithm will not match the one used by the built-in filter.

It turns out that accessing the filters from Python is very easy. The filters exist as simple functions that with the correct import are exceedingly easy to use. Conveniently, there is no change in the import path for Google App Engine as opposed to Django. Import the django.templates object defaultfilters and you are ready to go:

def slugify(string):
'''returns a URL-safe slug based on the provided string
Reuses the django template filter
'''
from django.template import defaultfilters
return defaultfilters.slugify(string)


Pretty simple, right?

One thing I will not talk about here (mostly since I haven't done it yet) is the process for supplementing the built in filters with your own custom filters. For those of you who are curious, read this informative blog entry.

If you have any feedback on this technique, let me know.

No comments:

Post a Comment