jinja2-humanize-extension – how to implement these into code?

Issue

I would like to use the humanize functions in my jinja2 flask app and the example from the documentation was too vague for me. I installed the extensions with pip and tried to implement them as follows:

What I would like to render is this:

<small class="text-muted">Time remaining: {{ ((submission.date_expiration - now)|naturaldelta()) }}</small>

Although I keep getting the error: jinja2.exceptions.TemplateAssertionError: No filter named 'naturaldelta'.

I added env = Environment(extensions=["jinja2_humanize_extension.HumanizeExtension"]) to my init.py but realized this isn’t adding the extensions properly. Does anyone have experience with this?

Solution

Guessing you’re getting that error when calling render_template from within your Flask app. I note that the full example in the extension’s docs, only mentions rendering with env.from_string.

How to register this on a normal Flask app? Seems you can set app.jinja_options once you’ve defined the app:

app = Flask(__name__)
app.jinja_options['extensions'] = ['jinja2_humanize_extension.HumanizeExtension']

I’m not actually sure if the above approach is "correct". I’d looked around for documentation on how to register a Jinja2 env on a Flask app, but couldn’t find much. Here’s how I did test this…

With some clues from this answer your Flask app should have an attribute app.jinja_options, which in my case with a fresh app was is empty dictionary:

>>> app = Flask(__name__)
>>> app.jinja_options
{}

So I add the extension with:

>>> app.jinja_options['extensions'] = ['jinja2_humanize_extension.HumanizeExtension']

Then verify:

>>> app.jinja_options
{'extensions': ['jinja2_humanize_extension.HumanizeExtension']}

Then test at the terminal with Flask’s render_template_string:

>>> from flask import render_template_string
>>> with app.app_context(): 
...  print( render_template_string('''{{300000|humanize_naturalsize()}}''', asd='abc'))
... 
300.0 kB

This should have the same effect when you’re template is rendered as standard with render_template

Answered By – v25

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published