I would like to add a filter to format my time, and best of all are filters like django timesince, which automatically displays the language of the selected i18n language, but first make a quick decision that I would like to format the Date. Proposed solution from the manual :
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 does not make the filter available in the template:
{{ ad.modified|datetimeformat }}
TemplateAssertionError: no filter named 'datetimeformat'
If I add the code to the Jinja2 library filters.py, then it will work. But I don’t need to add Jinja2 files manually, it should just add Jinja2 to mine app.yamland put my filter in my code, not in Jinja2 code. Where should I put the filter code?
thank
Update
My code looks like this and it seems the filter is not raised:
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