Montag, 21. April 2008

Using custom django template helpers with Google App Engine

This is dedicated to all you django lovers out there. If you wondered how to use custom filter functions with your Google App Engine applications, here you go:

Create a new file (I created mine in common/ to hold your template helper functions.

In this file, we need to register our custom filters, so:
# import the webapp module
from google.appengine.ext import webapp
# get registry, we need it to register our filter later.
register = webapp.template.create_template_register()
After we got the registry, we now can define our custom function:
def truncate(value,maxsize,stopper = '...'):
""" truncates a string to a given maximum
size and appends the stopper if needed """
stoplen = len(stopper)
if len(value) > maxsize and maxsize > stoplen:
return value[:(maxsize-stoplen)] + stopper
return value[:maxsize]
Then, we need to register our filter as following:
Now go to your bootstrap file (the one with your main function - in my case - see image above) and add the library (if you used a different module than common.templatefilters, you need to specifiy it here):
After adding this line of code, your template functions will get added to django and are available to use within your html templates:

This will truncate the variable somevar to 20 characters and add "..." to the end, if needed.


  1. One thing to note about this is that the final bit that you add to your must be at the top-level... NOT inside the main function!

  2. Also the shown must be created. Just an empty text file is fine.

  3. thank you that was of great help

  4. thank you that was of great help

  5. Great example - it's taken me days to get this far and your example is the simplest I've seen.

  6. Thx a lot! Clear & easy example!
    Now I got it :)

    in my case it works without
    my custom helper file resides in the application directory,
    argument of register_template_library just the helper file name, no path

  7. I needed to add
    from google.appengine.ext.webapp import template
    into the file.

    I also had to move the line:

    before the main() function.

    Thanks for writing this.

  8. Cool!
    It worked like a charm... Thanks!