Jinja2 Humanize Extension
jinja2-humanize-extension is a Jinja2 extension that integrates the popular `humanize` library, providing a suite of human-readable formatting filters directly within Jinja2 templates. It allows developers to easily format numbers, dates, and sizes (e.g., `naturalsize`, `naturaldate`, `intcomma`, `intword`) using Jinja's filter syntax. The current version is 0.4.0, with releases occurring periodically to maintain compatibility with its `humanize` dependency.
Warnings
- breaking Version 0.3.0 of `jinja2-humanize-extension` introduced compatibility with `humanize` library version 4.0 and later. Prior to v0.3.0 (specifically v0.2.1 and earlier), the extension was only compatible with `humanize < 4.0.0`.
- deprecated `humanize` version 4.0 deprecated `abs_timedelta` and `date_and_delta` functions. While `jinja2-humanize-extension` retains these as filters for compatibility, their future availability or behavior might be subject to changes in the `humanize` library itself.
- gotcha When integrating `jinja2-humanize-extension` with Flask, merely importing the extension might not make the filters available through `render_template`. The extension needs to be explicitly added to Flask's Jinja2 environment options.
Install
-
pip install jinja2-humanize-extension
Imports
- HumanizeExtension
from jinja2_humanize_extension import HumanizeExtension
- Environment
from jinja2 import Environment
Quickstart
from jinja2 import Environment
from jinja2_humanize_extension import HumanizeExtension
# We load the extension in a jinja2 Environment
env = Environment(extensions=[HumanizeExtension])
template = env.from_string(
"The file size is : {{ 30000000|humanize_naturalsize() }}\n"
"Today is: {{ '2023-01-15'|humanize_naturaldate() }}\n"
"Number with commas: {{ 1234567|humanize_intcomma() }}"
)
result = template.render()
print(result)
# Expected output:
# The file size is : 30.0 MB
# Today is: Jan 15th 2023
# Number with commas: 1,234,567