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
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: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