简体   繁体   中英

How do I register custom filter in Google App Engine template system?

According to Django documentation I've registered my filter:

from google.appengine.ext.webapp import template
# ...
register = template.create_template_register()
@register.filter(name='wld')
def wld(result):
    if result == 1 : return "win"
    if result == 0 : return "loss"
    if result == 0.5 : return "draw"
    return "unknown"
self.response.out.write(template.render("player.html", template_values))

somewhere in the template I have code:
{{result|wld}}

and when I try to render my template, I get the error: TemplateSyntaxError: Invalid filter: 'wld'

What am I doing wrong?

Once you have created your custom tag library, you need to register it with the Django template engine:

from google.appengine.ext.webapp import template
template.register_template_library('path.to.lib')

Note that the call template.register_template_library is a wrapper that is provided as part of the AppEngine SDK. Once you have put this in your main.py , the new tags or filters should be available in all of your templates without any further work. No need to use the {% load %} tag.

An important note: the functioning of register_template_library will vary depending on which version of Django you are using in your AppEngine application. If you are using 0.96, the parameter will be the path to the custom tags library file. If you are using Django 1.2, it will by a python module path to the custom tag library. I posted instructions for making this work in a post on my blog .

您需要在计划使用此过滤器的每个模板中添加{% load the_name_of_that_module %}块。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM