Python Method: % (Modulo, String Formatting)
n
% operator in Jinja2 is a string formatting tool that mirrors a legacy method in Python. It allows you to create dynamic strings by replacing placeholders (format specifiers) with variable values. This is a powerful way to inject data into a string for display, especially when you need to control the formatting of numbers.nn
nn
How It Works
nThe operator takes a format string on its left side and a variable or tuple of variables on its right. The format string contains placeholders, such as %s for a string, %d for an integer, or %f for a floating-point number. Jinja2 replaces these placeholders with the values provided on the right side.n
Syntax
n
{{ "format string with %s placeholder" % variable }}n{{ "format string with %s and %d placeholders" % (var1, var2) }}
nn
nn
Demonstration with Code Samples
nHere are a few examples of how to use the % operator in a Jinja2 application.n
1. Formatting with a Single String Value
nThis is a basic use case for inserting a variable into a sentence.nnJinja2 Templaten
{% set user_name = "Alice" %}n<p>{{ "Hello, %s!" % user_name }}</p>
nExplanation: The %s placeholder is replaced by the value of the user_name variable.nn
nn
2. Formatting with Multiple Values
nWhen you have more than one variable to insert, you must provide them as a tuple.nnJinja2 Templaten
{% set product_name = "Laptop" %}n{% set price = 1200.50 %}n<p>{{ "You have selected the %s, which costs $%.2f." % (product_name, price) }}</p>
nExplanation: This example uses a tuple (product_name, price) to provide values for two placeholders. The %.2f specifier formats the float to two decimal places.nn
nn
3. Using the printf Filter
nJinja2 also provides a more explicit printf filter that does the same thing, which can be easier to read.nnJinja2 Templaten
{% set user_score = 95 %}n<p>{{ "Your score is %d." | format(user_score) }}</p>
nExplanation: The format filter is another way to achieve the same result as the % operator, often preferred for its readability.nn
n
