Jinja Python Method: format()
n
format() method is a powerful and modern way to perform string formatting in Jinja2, mirroring Python’s str.format() method. It allows you to create dynamic strings by replacing bracketed placeholders ({}) with variable values. This is often the preferred method over the legacy % operator because of its improved readability and flexibility.nn
nn
How It Works
nThe format() method is a filter in Jinja2, which means you apply it to a string using the pipe (|) operator. The string being filtered contains placeholders ({}), which are then filled by the arguments passed to the format() method. You can use either positional or keyword arguments.n
Syntax
n
{{ "string with {} placeholders".format(arg1, arg2) }}n{{ "string with {name} placeholders".format(name=variable) }}
nn
nn
Demonstration with Code Samples
nHere are a few examples of how to use the format() method.n
1. Formatting with Positional Arguments
nThis is the simplest way to use format(). The values are placed into the placeholders in the order they are provided.nnJinja2 Templaten
{% set user_name = "Jane" %}n{% set user_id = 54321 %}n<p>Result: {{ "User: {}, ID: {}".format(user_name, user_id) }}</p>
nExplanation: The output will be "User: Jane, ID: 54321." The first {} is replaced by user_name, and the second by user_id.nn
nn
2. Formatting with Keyword Arguments
nUsing keyword arguments makes your template code more readable and self-documenting. The names in the placeholders must match the keyword arguments.nnJinja2 Templaten
{% set product = { 'name': 'Coffee Mug', 'price': 15.99 } %}n<p>Result: {{ "Product: {name}, Price: ${price:.2f}".format(name=product.name, price=product.price) }}</p>
nExplanation: The placeholder {name} is filled by product.name, and {price} is filled by product.price. The :.2f inside the {} is a format specifier, which tells Jinja2 to format the number as a float with two decimal places.nn
nn
3. Chaining with Other Filters
nThe format() method can be chained with other filters, allowing you to first format a string and then apply further transformations.nnJinja2 Templaten
{% set message = "welcome to our new site" %}n<p>Result: {{ "New user message: {}!".format(message) | upper }}</p>
nExplanation: First, format() inserts the message variable into the string. The resulting string, "New user message: welcome to our new site!", is then passed to the upper filter, producing a final output of "NEW USER MESSAGE: WELCOME TO OUR NEW SITE!".nn
