Custom filters in Google App Engine

I wanted to add custom filters to my Google App Engine application… There are instructions on how to do this in several places, but some of them contradict each other, and it took me a little while to get it working. Anyway, I thought I’d share the setup that did the trick for me.

Let’s say your application is in a directory app. Create a directory app/common. Drop an empty __init__.py in it, and the file containing your filters; say, my_filters.py.

Here’s some sample code for app/common/my_filters.py:

from google.appengine.ext import webapp

register = webapp.template.create_template_register()

@register.filter
def foobar(value):
    return "(%s)" % str(value)

This creates a simple (and rather useless :-) filter named foobar, that takes an argument and returns its string values, surrounded by parentheses. register.filter can be used as a decorator. Any functions in the file that are not registered, will not be recognized as filters.

In the application’s main file, add the following (at the toplevel):

from google.appengine.ext.webapp import template

template.register_template_library('common.my_filters')

Now, in your templates, you should be able to do things like

{{ "hello"|foobar }}

That’s all. I saw some explanations online that talked about using the templatetags directory and such, but that doesn’t seem to be necessary with App Engine.

3 Comments

  1. Ben said,

    January 28, 2009 @ 2:04 pm

    Thanks for posting this! Unforty for me I haven’t yet been able to get it to work. Any debugging hints for the below error message?

    TemplateSyntaxError: ‘my_filters’ is not a valid tag library: Could not load template library from django.templatetags.my_filters, No module named my_filters

  2. Ben said,

    January 28, 2009 @ 2:15 pm

    Never mind, it actually IS working and something else was throwing an error for me. Duh!

  3. Hans Nowak said,

    January 28, 2009 @ 5:30 pm

    Hm, did you include the template.register_template_library(‘common.my_filters’) part?

    Or, are you using the {% load … %} construct in your templates? (You don’t need it in this case.)

RSS feed for comments on this post