Adding a custom Jinja2 filter in GAE 1.6.0

2019-07-19 11:47发布

I'd like to add filter to format my time and the best would be filters like django's timesince that automatically outputs the language of the i18n selected language, but first to make a quick solution I'd like to format my date. The suggested solution from the manual is:

def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
    return value.strftime(format)

jinja_environment.filters['datetimeformat'] = datetimeformat

But adding this code to my file doesn't make the filter available in the template:

{{ ad.modified|datetimeformat }}
TemplateAssertionError: no filter named 'datetimeformat'

If I add the code to the Jinja2 library's filters.py then it works. But I shouldn't need to add to Jinja2 files manually, it should work just adding the Jinja2 to my app.yaml and put my filter in my code instead of in the Jinja2 code. Where should I put the filter code?

Thank you

Update

My code looks like this and it seems the filter is not picked up:

from django.utils import translation
from django.utils.translation import gettext, ngettext, ugettext, ungettext, get_language, activate
from jinja2 import Environment, FileSystemLoader

class DjangoTranslator(object):
    def __init__(self):
        self.gettext = gettext
        self.ngettext = ngettext
        self.ugettext = ugettext
        self.ungettext = ungettext

class DjangoEnvironment(jinja2.Environment):
    def get_translator(self, context):
        return DjangoTranslator()

jinja_environment = DjangoEnvironment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.i18n'])
jinja_environment.install_gettext_translations(translation)

def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
    return value.strftime(format)

jinja_environment.filters['datetimeformat'] = datetimeformat

2条回答
\"骚年 ilove
2楼-- · 2019-07-19 11:56

Following your example and Jinja2 docs I've added custom filter and it works. Make sure that you use proper jinja2.Environment instance for getting template and rendering:

env = jinja2.Environment(
    loader=jinja2.FileSystemLoader(template_path))
env.filters['default_if_none'] = default_if_none  # a function
tmpl = env.get_template(filename)
tmpl.render(**context)
查看更多
We Are One
3楼-- · 2019-07-19 12:03

Because I was using a cached jinja2 environment as recommended here,

Kee's answer didn't work for me, but this one did.

Specifically, adding the filter when calling webapp2.WSGIApplication

myconfig = {}
myconfig['webapp2_extras.jinja2'] =  {'template_path': ['templates','blog_posts'],
                                      'filters': {'blog_filter': blog_filter}}

app = webapp2.WSGIApplication(_routes,
    debug=True,
    config = myconfig)
查看更多
登录 后发表回答