Jinja2 Operator: ~ (Tilde)
n
~ operator in Jinja2 is a concatenation operator used to join multiple operands into a single string. When you use the tilde, Jinja2 automatically converts all operands (including numbers, boolean values, and other data types) into their string representation and then joins them together. This is a very convenient way to build dynamic strings and display them in your templates.nn
nn
How It Works
nThe tilde operator simplifies string building by handling type conversion for you. Instead of manually casting each variable to a string, you can simply use the ~ to combine them. This makes your template code cleaner and easier to read.n
Syntax
n
{{ string1 ~ variable ~ string2 }}
nIn this syntax, variable will be converted to a string and concatenated with string1 and string2.nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use the ~ operator in a Jinja2 application.n
1. Concatenating Strings and Variables
nA common use case is to construct a message that includes a variable value.nnJinja2 Templaten
<p>Hello, {{ user.first_name ~ " " ~ user.last_name }}!</p>nn<p>Your order total is: {{ "$" ~ order.total }}</p>
nExplanation: The first line concatenates a string, the user’s first name, a space, and their last name to form a full greeting. The second line adds a dollar sign prefix to the order.total value, which could be a number, but Jinja2 handles the conversion to a string for you.nn
nn
2. Building Dynamic URLs or CSS Classes
nThe tilde operator is perfect for creating dynamic attribute values, such as for links or CSS classes.nnJinja2 Templaten
<a href="/products/{{ product.id }}">View Product Details</a>nn<div class="user-status-{{ user.status }}">n <p>Current Status</p>n</div>
nExplanation: The first example builds a dynamic URL by concatenating a string with the product’s ID. The second example creates a dynamic CSS class like user-status-active or user-status-offline by joining the string "user-status-" with the user.status variable.nn
nn
3. Combining Different Data Types
nThe ~ operator’s automatic type conversion is particularly useful when you need to combine variables of different types.nnJinja2 Templaten
{% set is_active_user = True %}n<p>User is active: {{ is_active_user }}</p>n<p>User has been active for {{ active_days ~ " days" }}</p>
nExplanation: If active_days is an integer, the ~ operator converts it to a string before concatenating it with " days". Similarly, the boolean value is_active_user is converted to the string "True" for display.nn
n
