Jinja elif and else Statements
n
The Jinja2 elif and else statements are essential for creating templates that can handle multiple conditions. They extend the basic if statement to provide a clear, logical flow for different outcomes, much like in Python.
nn
The elif Statement
n
The elif (short for “else if”) statement is used to check an additional condition only if the preceding if or elif statements were false. You can have multiple elif blocks to chain together a series of sequential checks.
nn
{% if user.role == 'admin' %}
nWelcome, Administrator.n
n{% elif user.role == ‘editor’ %}n
nWelcome, Editor.n
n{% elif user.role == ‘moderator’ %}n
nWelcome, Moderator.n
n{% endif %}n
n
nn
The else Statement
n
The else statement provides a final, default option. This block of code will only be executed if all preceding if and elif conditions are false. It’s a great way to ensure that your template always renders a fallback message.
nn
{% if kenny.sick %}
nKenny is sick.n
n{% elif kenny.dead %}n
nYou killed Kenny! You bastard!!!n
n{% else %}n
nKenny looks okay — so far.n
n{% endif %}nn
n
