Jinja Format: filter function to apply string formatting
A Step-by-step Guide to JinjaformatFilter
The Jinja
filter is a tool for applying values to a "printf-style" format string. It's essentially a template-side version of Python's
operator or the
method, allowing you to insert variables into a string template. While Python's built-in string formatting methods are often more convenient and efficient, the
filter can be useful for keeping all of your formatting logic within the template itself.
How theformatFilter Works
filter takes a string that contains placeholders and replaces them with the values you provide. You can use either
-style placeholders or
-style curly brace placeholders. The filter accepts a variable number of positional arguments (
) and keyword arguments (
), depending on the formatting style you use. The basic syntax is as follows:
{{ "A string with a placeholder: %s" | format(my_variable) }}{{ "A string with a placeholder: {}" | format(my_variable) }}It's important to note that the
filter is primarily for compatibility and specific use cases. For most modern Jinja development, using Python's native formatting operators directly is the recommended approach for better readability and performance. For example,
is generally preferred over the filter syntax.
Practical Examples
Let's look at some examples to illustrate how the
filter can be used.
You can use the classic C-style
format strings with the
filter.
{% set name = "Alice" %}
{% set age = 30 %}
<p data-translate="true">{{ "Hello, my name is %s and I am %d years old." | format(name, age) }}</p><p data-translate="true">Hello, my name is Alice and I am 30 years old.</p>The filter replaces
with the string
with the integer
filter also supports the more modern
syntax with keyword arguments.
{% set product = "Jinja T-Shirt" %}
{% set price = 25.00 %}
<p data-translate="true">{{ "The {product} costs ${price:.2f}." | format(product=product, price=price) }}</p><p data-translate="true">The Jinja T-Shirt costs $25.00.</p>Here, the filter uses the keyword arguments to match the placeholders in the string, and the
specifier formats the price to two decimal places.
Conclusion
The Jinja
filter provides a flexible way to perform string formatting directly within your templates. While other methods might be more efficient or readable, this filter serves as a useful option for situations where you need to apply formatting to a variable that's already in the template's context. It's a valuable part of the Jinja toolkit, offering a simple way to create dynamic and well-structured strings.
Jump to