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/templatefilters.py) 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
else:
return value[:maxsize]
Then, we need to register our filter as following:
register.filter(truncate)
Now go to your bootstrap file (the one with your main function - in my case base.py - see image above) and add the library (if you used a different module than common.templatefilters, you need to specifiy it here):
webapp.template.register_template_library(
'common.templatefilters')
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.

Kommentare:

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

    AntwortenLöschen
  2. Also the __init__.py shown must be created. Just an empty text file is fine.

    AntwortenLöschen
  3. thank you that was of great help

    AntwortenLöschen
  4. thank you that was of great help

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

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

    @hairylarry:
    in my case it works without __init__.py:
    my custom helper file resides in the application directory,
    argument of register_template_library just the helper file name, no path

    AntwortenLöschen
  7. I needed to add
    from google.appengine.ext.webapp import template
    into the templatefilters.py file.

    I also had to move the line:
    webapp.template.register_template_library('common.templatefilters')

    before the main() function.

    Thanks for writing this.

    AntwortenLöschen
  8. Cool!
    It worked like a charm... Thanks!

    AntwortenLöschen