Jinja2 Pluralize Filters
Jinja2 Pluralize is a Python library that provides pluralization filters for Jinja2 templates. It offers both a simple filter based on `inflect.py` and a Django-style pluralize filter. Currently at version 0.3.0, released in 2015, the project appears to be in a maintenance state with infrequent updates.
Warnings
- gotcha The library's last release was in 2015, and it was officially tested up to Python 3.5. While it might function on newer Python versions, active support and compatibility with recent Jinja2 releases (e.g., Jinja2 3.x) are not guaranteed, potentially leading to unforeseen issues.
- gotcha The `pluralize_simple` filter relies on the `inflect` library for its functionality. However, `inflect` is not a declared dependency of `jinja2-pluralize`. If you intend to use `pluralize_simple`, you must install `inflect` separately (`pip install inflect`).
- gotcha Given the lack of recent maintenance, consider modern and actively developed alternatives like `jinja2-inflection` for pluralization and other string transformations, which provides a broader set of filters and better compatibility with current Python and Jinja2 versions.
Install
-
pip install jinja2-pluralize
Imports
- pluralize_dj
from jinja2_pluralize import pluralize_dj
- pluralize_simple
from jinja2_pluralize import pluralize_simple
Quickstart
from jinja2 import Environment
from jinja2_pluralize import pluralize_dj
env = Environment()
env.filters['pluralize'] = pluralize_dj
template = env.from_string('I have {{ count }} dog{{ count|pluralize }}.')
# Example 1: count = 1
result1 = template.render(count=1)
print(f"Rendered for count=1: {result1}") # Expected: I have 1 dog.
# Example 2: count = 2
result2 = template.render(count=2)
print(f"Rendered for count=2: {result2}") # Expected: I have 2 dogs.
template_args = env.from_string('There {{ num_items|pluralize("is", "are") }} {{ num_items }} item{{ num_items|pluralize }}.')
# Example 3: using custom singular/plural words
result3 = template_args.render(num_items=1)
print(f"Rendered for num_items=1: {result3}") # Expected: There is 1 item.
result4 = template_args.render(num_items=3)
print(f"Rendered for num_items=3: {result4}") # Expected: There are 3 items.