Jinja2 Literal Expression: Booleans
n
true or false. These are fundamental for controlling program flow and logic in your templates. The values `true` and `false` are always lowercase. For consistency with Python and to avoid past confusion, you can also use True and False, but the lowercase versions are generally preferred.nn
nn
How It Works
nBoolean values are used in conditional statements (e.g., `if`, `elif`, `else`) to determine which parts of a template should be rendered. A condition that evaluates to true will execute the associated code block, while one that evaluates to false will not. These literals are crucial for making dynamic decisions within a template.n
Syntax
n
{{ true }}n{{ false }}n{% if my_variable is True %}n ...n{% endif %}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use Boolean literals in a Jinja2 application.n
1. Using Booleans in an `if` Statement
nThis is the most common use case for booleans, where you conditionally display content based on a boolean value.nnJinja2 Templaten
{% set is_logged_in = true %}n{% if is_logged_in %}n <p>Welcome back!</p>n{% else %}n <p>Please log in to continue.</p>n{% endif %}
nExplanation: The `is_logged_in` variable is set totrue, so the `if` block is executed, displaying the “Welcome back!” message. If it werefalse, the “Please log in…” message would be displayed instead.nn
nn
2. Setting a Variable to a Boolean
nYou can set a variable directly to a boolean literal to use it later in your template, often in a condition or to display its value.nnJinja2 Templaten
{% set is_active_user = false %}n<p>User status:n{% if is_active_user %}n Activen{% else %}n Inactiven{% endif %}n</p>
nExplanation: The variable `is_active_user` is set to `false`. The `if` statement evaluates this and renders the `else` block, resulting in the output “User status: Inactive.”nn
nn
3. Using Booleans in a Comparison
nYou can also explicitly compare a variable to a boolean literal, though this is often redundant if the variable itself is already a boolean.nnJinja2 Templaten
{% set is_admin = True %}n{% if is_admin == true %}n <p>You have administrative privileges.</p>n{% endif %}
nExplanation: The `is_admin` variable is compared directly to the `true` literal. Since `True` and `true` are equivalent, the condition passes, and the message is displayed.nn
