Sling Academy
Home/FastAPI/How to use if/ else in Jinja

How to use if/ else in Jinja

Last updated: November 28, 2024

Jinja is a modern, designer-friendly templating engine for Python. It's often used with web frameworks like Flask, but its use isn't limited to web programming. One of the most common tasks in programming involves making decisions, and in templates, we accomplish this using if and else statements. Let's dive into how we can leverage these in Jinja templates.

Basic if Statement

The simplest form of conditional execution in Jinja is through the if statement. You can use it to conditionally include or omit certain pieces of template output depending on the state of the variables in your context.

{% if user %}
    Hello, {{ user.name }}!
{% endif %}

In this example, if user is defined and not None, the paragraph welcoming the user will be rendered. If not, nothing will be displayed.

Using else with if

You can also specify a block of code to run if the condition in the if statement does not hold. This is done using an else block.

{% if user %}
    Hello, {{ user.name }}!
{% else %}
    Hello, Guest!
{% endif %}

In this example, if the user is not defined, a default welcome message for a guest is shown.

Elongating Conditions with elif

Just like in traditional programming, Jinja supports elif to create further branching paths in logic.

{% if user.is_admin %}
    Admin Panel
{% elif user.is_editor %}
    Editor Dashboard
{% else %}
    User Dashboard
{% endif %}

This example checks the roles of a user. If a user is an admin, they see the Admin Panel; if they are an editor, they see the Editor Dashboard; otherwise, a default User Dashboard is shown.

Truthiness in Jinja

Jinja follows Python’s rules on what values evaluate to True or False. For instance, an empty string, 0, None, and empty list evaluate to False. This means you can use including expressions directly:

{% if mylist %}
    List has items!
{% else %}
    List is empty!
{% endif %}

Here's a check to see if a list is empty or not and print a corresponding message.

Conclusion

The use of if, else, and elif statements within Jinja templates allows for a dynamic and responsive rendering of HTML documents. By controlling the flow of template rendering, you can build templates that adapt to different contexts and user inputs effectively. By mastering these conditionals, you enhance how data is presented, ultimately contributing to better user experiences.

Next Article: How to use namespace in Jinja

Previous Article: How to use loops in Jinja

Series: Jinja Templates

FastAPI

You May Also Like

  • Popular useful built-in Jinja filters you should know
  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • FastAPI + Jinja: How to create custom filters
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to create and use macros in Jinja
  • How to use namespace in Jinja
  • How to use loops in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict
  • Resolving the FastAPI Circular References Error