Jinja If: elif and else
JinjaelifandelseStatements
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.
TheelifStatement
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.
{% if user.role == 'admin' %}Welcome, Administrator.
{% elif user.role == 'editor' %}
Welcome, Editor.
{% elif user.role == 'moderator' %}
Welcome, Moderator.
{% endif %}
TheelseStatement
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.
{% if kenny.sick %}Kenny is sick.
{% elif kenny.dead %}
You killed Kenny! You bastard!!!
z[
Kenny looks okay — so far.
{% endif %}
Jump to