How to use if else condition in Django templates (Ultimate guide)

Share your love

With if-else conditional checking in your Django templates, you can evaluate expressions and execute different blocks of code based on the state of data.

You can effectively use if-else conditions in Django templates to create dynamic and flexible HTML pages by following these steps:

Step 1. Open a .html file and select a section you wish to add an if statement

Step 2. Within the file, use the if statement inside the HTML markup, like this:

{% if some_condition %}
    <p>Some content here</p>
{% endif %}

Step 3. Chain the if conditions using elif if you want to have multiple conditions

{% if some_condition %}
    do something
{% elif some_other_condition %}
    do something else
{% elif another_condition %}
    do another thing
{% else %}
    do something entirely different
{% endif %}

Step 4. Remember to end your if tag with the {% endif %} tag

...
{% endif %}

As a developer, I remember a time when I was working on a Django project that required me to display different content to users based on their login status. I needed to use if-else conditions to check whether a user was logged in or not and display different content accordingly.

However, I was unfamiliar with the syntax and the various types of conditions that could be used in Django templates.

After a bit of research and experimentation, I finally figured out how to use if-else conditions in Django templates effectively.

Whether you are new to Django or an experienced developer, this guide will help you master if-else conditions in Django templates and make your web applications more powerful and dynamic.

What is an if else condition in Django templates?

An “if else” condition in Django template is a programming structure that allows developers to display content or perform actions based on certain conditions in a .html file.

Essentially, an if statement allows you to write code that asks “if this condition is true, do this thing, otherwise, do this other thing.”

This is really useful for creating dynamic and customized web pages that adapt to different scenarios, users, current page users are on, or generally user needs.

In Django, the syntax for an “if else” condition in templates is simple and easy to use, allowing developers to integrate complex logic into their HTML without needing to write a lot of additional code.

The syntax of an if else condition in Django template

The syntax of an if-else condition in Django templates follows a programming structure that checks whether a condition is true or false, and executes different blocks of code accordingly.

Here’s the basic syntax for an if-else condition in Django templates:

{% if some_condition %}
    do something
{% else %}
    do something else
{% endif %}
  • Wrap the keyword if inside the template tag syntax, {% %}
  • The {% if %} statement begins the if-else condition, and is followed by the condition that you want to check. This condition can be any valid Python expression or variable.
  • The code block that follows the if statement is executed if the condition is true.
  • The {% else %} statement begins the block of code that will be executed if the condition is false.
  • The code block that follows the else statement is executed if the condition is false.
  • End the if block with an {% endif %} template tag

Here’s an example of how you might use this syntax in a Django template to check if a user is logged in:

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% else %}
    <p>Please log in to continue.</p>
{% endif %}

The syntax is easy to use, and allows developers to write code that integrates complex logic into their HTML without needing to write additional code. It’s a useful tool for creating customized web pages that adapt to different scenarios or user needs.

The syntax of an if elif else condition in Django template

Here’s the basic syntax for an if-elif-else condition in Django templates:

{% if condition1 %}
    do something
{% elif condition2 %}
    do something else
{% else %}
    do something else entirely
{% endif %}
  • Wrap the keyword if inside the template tag syntax, {% %}
  • The {% if %} statement begins the if-elif-else condition, and is followed by the first condition that you want to check. This condition can be any valid Python expression or variable.
  • The code block that follows the if statement is executed if the first condition is true.
  • The {% elif %} statement begins the next condition that you want to check. You can have as many {% elif %} statements as you need.
  • The code block that follows the elif statement is executed if the second condition is true.
  • The {% else %} statement begins the block of code that will be executed if all previous conditions are false.
  • The code block that follows the else statement is executed if all previous conditions are false.
  • End your if block with, {% endif %}

Here’s an example of an if-elif-else condition in a Django template that checks the episodes of the Star Wars movies and their names:

if-elif-else condition in a Django template that checks the episodes of the Star Wars movies and their names
{% if episode == 4 %}
    <p>This is the fourth Star Wars movie that was released, and it's known as "A New Hope".</p>
{% elif episode == 5 %}
    <p>This is the fifth Star Wars movie that was released, and it's known as "The Empire Strikes Back".</p>
{% elif episode == 6 %}
    <p>This is the six Star Wars movie that was released, and it's known as "Return of the Jedi".</p>
{% else %}
    <p>This is not one of the original Star Wars movies.</p>
{% endif %}

You can read more about elif branches in this article I have written.

Why use if else in Django templates?

Using if else statements in Django templates is crucial for creating dynamic and customized web pages.

Here are a few reasons why you might want to use if else statements in Django templates:

  1. Show or hide content: If else statements can be used to display or hide content based on certain conditions, such as whether a user is logged in or not.
  2. Control page flow: By using if else statements in your templates, you can control the flow of your application based on certain conditions, such as the results of a database query.
  3. Personalize content: If else statements can be used to personalize the content on your web pages based on user preferences, location, or other factors.
  4. Simplify code: By using if else statements in your templates, you can simplify your code and reduce the need for complex logic in your views.

How to use if condition in Django templates?

To use an if condition, you need to create one in your template files using the syntax highlighted above. Basically, adding an if condition to your Django template is a relatively simple process. By using the syntax provided, you can create dynamic and customized web pages that respond to user input, display different content based on the current state of your application, and provide a better user experience for your visitors.

Here’s a detailed process for creating an effective if else condition in your Django templates.

How do you add an if condition in HTML templates

  1. Create a new HTML file or open an existing one that you want to add an if condition to.
  2. In the .html file, create an if block by using the following syntax: {% if condition %} content {% endif %}. Replace “condition” with the statement you want to evaluate, and “content” with the HTML code you want to display if the condition is true.
  3. Within the if block, you can add any valid HTML code. For example, you could include an image, an h2, a link, a paragraph of text, or any other HTML tag.
  4. Save the HTML file and run your Django application to see the results.
  5. If you want to add an “else” block to your if statement, you can use the following syntax: {% if condition %} content {% else %} alternate content {% endif %}. Replace “alternate content” with the HTML code you want to display if the condition is false.
  6. You can also use “elif” to add additional conditions to your if statement. The syntax for this is: {% if condition1 %} content {% elif condition2 %} other content {% else %} alternate content {% endif %}.
  7. When you are done with your if statement, be sure to close it with {% endif %}.

Let’s see how if-else conditions can be used in a real-world Django application.

Examples of if conditions in Django templates

When building a web application using Django, it’s common to use if conditions in your templates to make your web pages more dynamic and responsive. By using if conditions, you can display different content based on user input, the state of your application, or any other condition you choose.

There are many different types of if conditions you can use in Django templates. In this section, we’re going to look at:

  1. Conditions that check if a variable is empty,
  2. Conditions that check if a string is equal to another string, and
  3. Conditions that check if a value is in a list.

Let us explore some examples of these different types of if conditions and see how they can be used to create more powerful and flexible web pages in Django.

1. Django template if condition equal string

“Django template if condition equal string” is an if condition that checks if a given variable in the Django template is equal to a specific string. The “if” statement can be used to check if a variable equals a specific string, using the “==” operator.

You might use this condition to display different content depending on the value of a variable.

For example, let’s say we have a variable called “favorite_movie”, which holds a string value of the user’s favorite movie. We want to display a message only if the user’s favorite movie is “Star Wars”. We can use an “if” statement to check this condition.

{% if favorite_movie == "Star Wars" %}
    <p>May the force be with you!</p>
{% endif %}

As for a real-world scenario, let’s consider I am building a movie review website.

When a user writes a review for a movie, they may include a rating for the movie as a string, such as “5 stars” or “4 out of 5”.

To display the overall rating of a movie, we can use an “if” statement to check if the rating matches a certain string.

For instance, to display a “Best rated” rating for a movie, we can check if the rating is “5 stars” or “4.5 stars”, and display the “best” icon accordingly:

{% if rating == "5 stars" or rating == "4.5 stars" %}
    <img src="best.png" alt="Best rated" />
{% endif %}

This technique can be applied to various other scenarios, such as displaying an “approved” icon for a comment or user application that has been approved by a moderator, or displaying a “sale” badge for products that are on sale.

2. Django template if not

Django template if not” is an if condition that checks if a variable is not true, or is false. Besides, check if a variable does not exist.

You might use this condition to check if a user has not yet completed a certain action or to hide certain content until a user has completed a certain task.

Let’s say you have a blog that allows users to post comments.

You want to display a message that says “No comments yet” if there are no comments for a particular blog post.

You can use the following code in your Django template for displaying single article:

{% if not comments %}
    <p>No comments yet</p>
{% endif %}

In this example, the “if not” statement checks if the “comments” variable is empty or does not exist. If it is empty or does not exist, the message “No comments yet” is displayed.

3. Django template if equals

Django template if equals” is an if condition that checks if two variables are equal. You might use this condition to display different content depending on the values of two different variables.

For example, you might use it to check if a user-provided password1 is the same as password2.

For example of how you might use the “if equals” statement in Django templates is to display a message to a user based on their account status.

For instance, in Star Wars, you could use this statement to determine if a user is a Jedi or not.

Here’s an example of how the code might look:

{% if user.status == "Jedi" %}
    <p>Welcome, Jedi. May the Force be with you.</p>
{% else %}
    <p>Welcome, Padawan. Keep training to become a Jedi.</p>
{% endif %}

4. Django template if in list

Django template if in list” is an if condition that checks if a variable is in a list. You can check if a particular value exists within a list using the in operator.

You might use this condition to display different content depending on whether a user has selected a specific option or not.

For example, you might use it to check if a user has selected a specific item from a dropdown list and display different content depending on the result.

Another example, in a movie website, you may want to display different movie reviews based on the genre of the movie.

You can define a list of genres and check if a particular movie belongs to a certain genre using the in operator in the Django template.

Here’s an example code snippet:

<!-- movie_review.html -->

{% if 'comedy' in movie.genres %}
    <p>This is a comedy movie.</p>
{% elif 'drama' in movie.genres %}
    <p>This is a drama movie.</p>
{% elif 'action' in movie.genres %}
    <p>This is an action movie.</p>
{% else %}
    <p>This movie does not belong to any genre.</p>
{% endif %}

5. Django template if to check if a variable is empty

Django template if to check if a variable is empty” is an if condition that checks if a variable has no value or is empty. You might use this condition to display different content depending on whether a variable has a value or not.

For example, you might use it to display a message to a user if they haven’t entered any data into a form field.

For example, let’s say you are building a website for a Star Wars fan club, and you want to display the names of the top three members based on the number of likes they have received on their posts.

You might have a members list with the names and likes of all members. Besides, want to display only the top three names.

You can use the if statement to check if a member has received any likes, and only display their name if they have.

Here’s an example of how to use if to check if a variable is empty in a Django template:

{% if members %}
    <ol>
    {% for member in members|slice:":3" %}
        {% if member.likes %}
            <li>{{ member.name }}</li>
        {% endif %}
    {% endfor %}
    </ol>
{% else %}
    <p>No members found.</p>
{% endif %}

In this example, we first check if the members list is not empty using {% if members %}.

If it is not empty, we display an ordered list using the ol tag.

We then loop through the first three members in the list using

{% for member in members|slice:":3" %}

Inside the loop, we use the if statement to check if the member has received any likes using

{% if member.likes %}

and only display their name using {{ member.name }} if they have.

Finally, we close the loop and the ol tag.

      {% endfor %}
    </ol>

If the members list is empty, we display a message saying “No members found.” using

 {% else %} 
    <p>No members found.</p>
 {% endif %}
Django template if to check if a variable is empty

Multiple if conditions in Django templates

In some cases, a single if condition may not be enough to fully evaluate a particular situation in a Django template. This is where multiple if conditions come into play. By using multiple if conditions, you can evaluate more complex situations and make decisions based on various criteria.

How do you add multiple if conditions in Django templates

To add multiple if conditions in Django templates, you can simply chain them together using the {% if %} template tag.

Here are the steps to add multiple if conditions in Django templates:

  1. Open your Django template file in your code editor.
  2. Identify the point in your HTML where you want to add the first if condition.
  3. Insert the {% if %} template tag followed by the condition you want to check, enclosed in quotes. For example, {% if name == "Luke" %}.
  4. Add the code you want to execute if the condition is true between the {% if %} and {% endif %} tags.
  5. Add another {% if %} tag with the next condition you want to check, if necessary.
  6. Continue adding additional {% if %} tags as needed for each additional condition you want to check.
  7. Close each {% if %} tag with an {% endif %} tag.
  8. Save your file.

Example multiple if conditions in HTML templates

Let’s say you want to create a Star Wars-themed website and you have a page where you want to display information about different characters.

You want to display a different message depending on whether the character is a

  • Jedi,
  • a Sith,
  • or neither.

You can use multiple if conditions in your Django template to achieve this.

Here’s how you can use multiple if conditions in your Django template to display different messages for different characters:

{% if character.side == "Jedi" %}
    <p>{{ character.name }} is a Jedi.</p>
{% endif %}

{% if character.side == "Sith" %}
    <p>{{ character.name }} is a Sith.</p>
{% endif %}

{% if character.side != "Jedi" and character.side != "Sith" %}
    <p>{{ character.name }} is neither a Jedi nor a Sith.</p>
{% endif %}

In this example, we check if the character object’s side attribute is equal to “Jedi”, “Sith”, or neither, and displays a different message depending on the result.

We use the != operator to check if side is not equal to “Jedi” and not equal to “Sith”.

Best practices for using if else statements in Django templates

When working with if else statements in Django templates, it’s important to follow certain best practices to ensure that your code is

  1. Readable,
  2. Maintainable, and
  3. Efficient.

Here are some best practices for using if else statements in Django templates:

  1. Keep your code simple and straightforward: Avoid using overly complicated if else statements, as they can make your code difficult to read and maintain.
  2. Avoid creating complex and deeply nested if statements. While nested if else statements can be useful in certain situations, it’s generally best to avoid them as they can quickly become difficult to read and maintain.
  3. Use template filters and tags to simplify your code: Django provides a number of built-in filters and tags that can help simplify your if else statements and make your code more concise.
  4. Where necessary, add some comments explaining the logic behind a conditional if else check

Share your love
Badi
Badi

Badi here, creator of ngangasn.com— A website dedicated to providing helpful information and how-to's of web development and hosting. Inspired by a fascination to write the most efficient code to make a computer laugh, & humans, Steve has a passion for organizing characters to create code and informative content.
What makes me happy?
Well, nothing like the feeling of finally figuring out that one pesky bug that's been driving me crazy.

Leave a Reply

Your email address will not be published. Required fields are marked *