Examples
Jinja Conditional Template
Rendering a Conditional Template
Jinja conditional template uses {% if %} for dynamic content.
Introduction to Jinja Conditional Templates
Jinja is a popular templating engine for Python, widely used in web development to render HTML with dynamic content. Conditional statements in Jinja allow templates to change content based on variables, creating a dynamic and responsive user experience. The primary tool for conditional logic in Jinja is the {% if %}
statement.
Basic Usage of {% if %} in Jinja
The {% if %}
statement in Jinja is used to execute code blocks only if a specified condition is true. It is similar to the if
statement in Python. Here is a basic example of how to use it in a Jinja template:
In this example, the template checks if the user
is authenticated. If the condition is true, it displays a welcome message with the user's username. Otherwise, it prompts the user to log in.
Using {% elif %} for Multiple Conditions
In scenarios where multiple conditions need to be evaluated, Jinja provides the {% elif %}
statement, which stands for "else if". This allows for additional conditions to be checked if the previous {% if %}
condition is false.
This example evaluates a score
variable to assign letter grades. It checks multiple ranges using {% elif %}
and defaults to an 'F' if none of the conditions are met.
Combining Conditions with Logical Operators
Jinja allows for combining multiple conditions using logical operators like and
, or
, and not
. This capability is useful for complex logic checks.
In this template, an additional check ensures that the user is an admin. The message changes accordingly based on the user's authentication and admin status.
Nested Conditions for Complex Logic
Jinja also supports nested conditions, allowing for more complex logic within templates. This can be useful when decisions depend on multiple layers of conditions.
In this example, once a user is authenticated, another nested condition checks if they have notifications, displaying an appropriate message.
Examples
- Previous
- Loop Template
- Next
- Macro Template