Jinja2 Strcase
jinja2-strcase is a Python package that provides a set of filters for converting string cases within Jinja2 templates, including common formats like snake_case, kebab-case, and camelCase. It is currently at version 0.0.2 and is a port of the Go `strcase` package. The package has an 'Alpha' development status, indicating it is not yet stable for production use.
Warnings
- breaking The package is currently in 'Development Status :: 3 - Alpha'. This means the API might change significantly in future versions without maintaining backward compatibility.
- gotcha Jinja2 extensions, including jinja2-strcase, need to be explicitly loaded into the Jinja2 Environment via the `extensions` parameter. Forgetting this step will result in template filter not found errors.
- gotcha When using Jinja2 templates, if a variable or attribute does not exist, it will return an undefined value. Operations on undefined values, or attempting to iterate over non-iterable objects, can lead to `NoneType` errors.
- gotcha Comparing different data types (e.g., string and integer) directly in Jinja2 templates without proper type conversion can lead to runtime errors.
Install
-
pip install jinja2-strcase
Imports
- StrcaseExtension
from jinja2_strcase import StrcaseExtension
- Environment
from jinja2 import Environment
Quickstart
from jinja2 import Environment
from jinja2_strcase import StrcaseExtension
# Create a Jinja2 environment and load the StrcaseExtension
env = Environment(extensions=[StrcaseExtension])
# Define a template using the 'to_snake' filter
template = env.from_string("{{ 'Any kind of string' | to_snake }}")
print(f"to_snake: {template.render()}")
# Example with another filter: to_screaming_snake
template_screaming_snake = env.from_string("{{ 'Another Test String' | to_screaming_snake }}")
print(f"to_screaming_snake: {template_screaming_snake.render()}")
# Example with to_camel
template_camel = env.from_string("{{ 'this is a camel case' | to_camel }}")
print(f"to_camel: {template_camel.render()}")