How do I register custom filter in Google App Engi

2019-02-13 22:51发布

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?

2条回答
Ridiculous、
2楼-- · 2019-02-13 23:34

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.

查看更多
爷、活的狠高调
3楼-- · 2019-02-13 23:42

You need to add {% load the_name_of_that_module %} block in every template you plan to use this filter.

查看更多
登录 后发表回答