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 moduleAfter we got the registry, we now can define our custom function:
from google.appengine.ext import webapp
# get registry, we need it to register our filter later.
register = webapp.template.create_template_register()
def truncate(value,maxsize,stopper = '...'):Then, we need to register our filter as following:
""" 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]
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(After adding this line of code, your template functions will get added to django and are available to use within your html templates:
'common.templatefilters')



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öschenAlso the __init__.py shown must be created. Just an empty text file is fine.
AntwortenLöschenthank you that was of great help
AntwortenLöschenthank you that was of great help
AntwortenLöschenGreat example - it's taken me days to get this far and your example is the simplest I've seen.
AntwortenLöschenThx a lot! Clear & easy example!
AntwortenLöschenNow 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
I needed to add
AntwortenLöschenfrom 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.
Thanks!
AntwortenLöschenCool!
AntwortenLöschenIt worked like a charm... Thanks!