A Jinja2 extension that integrates the inflection library's string transformation functions as template filters
Project description
jinja2-inflection
A Jinja2 extension that integrates the inflection library's string transformation functions as template filters.
Overview
jinja2-inflection is a Jinja2 extension that provides a set of filters for string transformation using the inflection library. This package allows you to easily manipulate strings in your Jinja2 templates by converting between different naming conventions, pluralizing words, and more.
Key Features
- String Transformation Filters: Access a variety of filters that apply
inflectionfunctions to strings in templates. - Easy Integration: Seamlessly add the extension to your Jinja2 environment, making the filters available in all templates.
- Reusable Logic: Encapsulate
inflectionfunctions as filters to promote code reuse and consistency across templates. - Parameter Support: Filters support optional parameters for customized string transformations.
Filters
The extension provides the following filters:
| Filter | Description | Example |
|---|---|---|
camelize |
Converts strings to CamelCase | {{ 'product_category' | camelize }} → ProductCategory |
dasherize |
Replaces underscores with dashes | {{ 'first_name' | dasherize }} → first-name |
humanize |
Makes text more human-readable | {{ 'employee_salary' | humanize }} → Employee salary |
ordinal |
Returns the ordinal suffix for a number | {{ 1 | ordinal }} → st |
ordinalize |
Turns a number into an ordinal string | {{ 1 | ordinalize }} → 1st |
parameterize |
Replaces special chars with hyphens | {{ 'Donald E. Knuth' | parameterize }} → donald-e-knuth |
pluralize |
Returns the plural form of a word | {{ 'octopus' | pluralize }} → octopi |
singularize |
Returns the singular form of a word | {{ 'mice' | singularize }} → mouse |
tableize |
Creates a table name from a class name | {{ 'UserAccount' | tableize }} → user_accounts |
titleize |
Capitalizes words in a string | {{ 'api_responses' | titleize }} → Api Responses |
transliterate |
Replaces non-ASCII characters | {{ 'café' | transliterate }} → cafe |
underscore |
Makes an underscored version | {{ 'DeviceType' | underscore }} → device_type |
Filters with Parameters
Some filters support optional parameters:
- camelize:
{{ 'product_category' | camelize(uppercase_first_letter=False) }}→productCategory - parameterize:
{{ 'Donald E. Knuth' | parameterize(separator='_') }}→donald_e_knuth
Installation
Using pip
pip install jinja2-inflection
Using uv
uv pip install jinja2-inflection
Using Poetry
poetry add jinja2-inflection
Using PDM
pdm add jinja2-inflection
Usage
Basic Usage
from jinja2 import Environment
from jinja2_inflection import InflectionExtension
# Set up Jinja2 environment with the extension
env = Environment(extensions=[InflectionExtension])
# Use filters in templates
examples = [
# Basic string transformations
"{{ 'snake_case_string' | camelize }}", # Outputs: "SnakeCaseString"
"{{ 'first_name' | dasherize }}", # Outputs: "first-name"
"{{ 'employee_salary' | humanize }}", # Outputs: "Employee salary"
"{{ 'DeviceType' | underscore }}", # Outputs: "device_type"
# Number transformations
"{{ 1 | ordinal }}", # Outputs: "st"
"{{ 2 | ordinalize }}", # Outputs: "2nd"
# Pluralization and singularization
"{{ 'octopus' | pluralize }}", # Outputs: "octopi"
"{{ 'mice' | singularize }}", # Outputs: "mouse"
# Other transformations
"{{ 'UserAccount' | tableize }}", # Outputs: "user_accounts"
"{{ 'api_responses' | titleize }}", # Outputs: "Api Responses"
"{{ 'café' | transliterate }}", # Outputs: "cafe"
# Using parameters
"{{ 'product_category' | camelize(uppercase_first_letter=False) }}", # Outputs: "productCategory"
"{{ 'Donald E. Knuth' | parameterize(separator='_') }}", # Outputs: "donald_e_knuth"
]
# Render and print each example
for example in examples:
template = env.from_string(example)
print(f"{example} → {template.render()}")
Using with FastAPI
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from jinja2_inflection import InflectionExtension
app = FastAPI()
# Configure Jinja2Templates with the extension
templates = Jinja2Templates(directory="templates")
templates.env.add_extension(InflectionExtension)
@app.get("/")
async def index(request: Request):
return templates.TemplateResponse(
"index.html", {"request": request, "snake_case_var": "user_profile"}
)
In your template (templates/index.html):
<!DOCTYPE html>
<html>
<head>
<title>FastAPI with jinja2-inflection</title>
</head>
<body>
<h1>Variable in CamelCase: {{ snake_case_var | camelize }}</h1>
<!-- Outputs: Variable in CamelCase: UserProfile -->
</body>
</html>
Using with Starlette
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.templating import Jinja2Templates
from starlette.requests import Request
from jinja2_inflection import InflectionExtension
# Configure Jinja2Templates with the extension
templates = Jinja2Templates(directory="templates")
templates.env.add_extension(InflectionExtension)
async def homepage(request: Request):
return templates.TemplateResponse(
"index.html", {"request": request, "table_name": "user_accounts"}
)
routes = [Route("/", homepage)]
app = Starlette(debug=True, routes=routes)
Using with Flask
from flask import Flask, render_template
from jinja2_inflection import InflectionExtension
app = Flask(__name__)
app.jinja_env.add_extension(InflectionExtension)
@app.route("/")
def index():
return render_template(
"index.html"
) # Now your templates can use inflection filters
Using with Django
In your Django settings:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [...],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'myapp.jinja2.environment',
...
},
},
]
Then in myapp/jinja2.py:
from jinja2 import Environment
from jinja2_inflection import InflectionExtension
def environment(**options):
env = Environment(**options)
env.add_extension(InflectionExtension)
return env
Requirements
- Python 3.13+
- Jinja2 3.1.6+
- inflection 0.5.1+
License
BSD-3-Clause
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Acknowledgments
- This project uses the inflection library to provide powerful string transformation capabilities. Special thanks to the contributors of the inflection library for their work.
- Additionally, we acknowledge the Jinja2 project for providing a robust templating engine that makes this extension possible.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file jinja2_inflection-0.6.1.tar.gz.
File metadata
- Download URL: jinja2_inflection-0.6.1.tar.gz
- Upload date:
- Size: 140.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cbca76dd88d7005ff13c419fcd695a5e88b83d8bd27f0e2f8d9d29acff0e3e6a
|
|
| MD5 |
5ca0975b9fcea19ae1fa3ba75b16e1b0
|
|
| BLAKE2b-256 |
aa55e12374f3f1ada78b8b0e684ce2d3796fc5e22cc49902dd798ccf22b62854
|
File details
Details for the file jinja2_inflection-0.6.1-py3-none-any.whl.
File metadata
- Download URL: jinja2_inflection-0.6.1-py3-none-any.whl
- Upload date:
- Size: 5.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
64b61d7842d976694576f8884b46301f3d6ce41dc87bd3b53af5df36118edac2
|
|
| MD5 |
9eb26dbfbfc426e03693b5dad1634a68
|
|
| BLAKE2b-256 |
f6049815e0aada2e2c742b08e97bc9735b023787ef0985d96674223792e958b6
|