How to create nested if else statements in Django templates

Share your love

As a developer, you will undoubtedly encounter complex situations that require nested if else statements in your Django templates. There will be situations where you will need to include multiple if statements nested together to achieve the desired functionality.

Let’s explore how you can use nested if conditions to create readable, and maintainable code.

How to create nested if conditions in Django templates

One of the most important features of Django templates is the ability to use nested if conditions to handle complex logic.

With nested if conditions or multiple {% elif %} statements, you can create customized templates that display different content based on specific conditions.

Allow me to show you how to create nested if conditions in Django templates, step by step. Here’s a generalized example step by step:

Step 1: Declare the {% if %} tag with a condition provided as an argument to the if tag: {% if condition %}

Example:

{% if some_variable > 5 %}

Step 2: Add any additional {% if %} tags nested within the parent tag: {% if another_condition %}

Example:

<!-- first if tag -->
{% if some_variable > 5 %} 
    <!-- another if tag inside the first if tag -->
    {% if another_variable == "something" %} 
        <p>This text will only display if both conditions are met.</p> 
    {% endif %} 
    
{% endif %}

Step 3: Close each {% if %} tag with the {% endif %} tag: {% endif %}

Example:

<!-- first if tag -->
{% if some_variable > 5 %} 
    <!-- another if tag inside the first if tag -->
    {% if another_variable == "something" %} 
        <p>This text will only display if both conditions are met.</p> 
            <!-- another if tag inside the first if tag can be added here -->
            ...
    {% endif %} 
    <!-- another if tag inside the first if tag can be added here -->
    ...
{% endif %}

Examples of nested if conditions in HTML templates

Example 1: Checking user authentication and role

This is an example that you will most likely use when authenticating users on your Django website:

Create a template file

The first step in creating nested if conditions in Django templates is to create a new template file. You can create a new file in your Django project’s templates directory.

Declare template tags:

Start by adding the parent if statement

To create a basic nested if statement, you’ll need to start with a parent if statement. For example, you could create an if statement that checks if a user is logged in:

{% if user.is_authenticated %}

Add other if tags as child tags to the parent if tag

To create a nested if statement, you’ll need to add additional if statements within the parent if statement.

For example, you could add an if statement that checks if the user is an administrator:

{% if user.is_authenticated %}
   {% if user.is_superuser %}
      <p>Welcome, administrator!</p>

Close all your if tags with the endif tag for all nested branches and parent

Finally, make sure to close all if statements with the {% endif %} tag. For example, you can close the nested if statement from step 4 like this:

{% if user.is_authenticated %}
   {% if user.is_superuser %}
      <p>Welcome, administrator!</p>
   {% endif %}

And then close the parent if statement from step 3 like this:

css
{% if user.is_authenticated %}
   {% if user.is_superuser %}
      <p>Welcome, administrator!</p>
   {% endif %}
{% endif %}

Example 2: Display different content based on the page is on

We can also use nested if conditions to display different content based on the page the user is on. This is a common use case for Django templates, especially on larger websites with many pages.

Let’s say we have a website with a home page, a products page, and a contact page. You want to display different content in the sidebar based on the page the user is on.

On the home page, we might want to display links to our most popular products.

On the products page, we might want to display links to our different product categories.

And on the contact page, we might want to display our business address and phone number.

Here’s an example code implementation of how we might implement this using nested if conditions in a Django template:

In home.html:

<!-- in home.html -->
{% extends "base.html" %}

{% block content %}
    <h1>Welcome to our website!</h1>
{% endblock %}

{% block sidebar %}
    {% if request.path == "/" %}
        <h2>Our most popular products</h2>
        <ul>
            <li>Product 1</li>
            <li>Product 2</li>
            <li>Product 3</li>
        </ul>
    {% endif %}
{% endblock %}

In products.html:

<!-- products.html -->
{% extends "base.html" %}

{% block content %}
    <h1>Our Products</h1>
{% endblock %}

{% block sidebar %}
    {% if request.path == "/products/" %}
        <h2>Product Categories</h2>
        <ul>
            <li>Category 1</li>
            <li>Category 2</li>
            <li>Category 3</li>
        </ul>
    {% endif %}
{% endblock %}

In contact.html:

<!-- contact.html -->
{% extends "base.html" %}

{% block content %}
    <h1>Contact Us</h1>
{% endblock %}

{% block sidebar %}
    {% if request.path == "/contact/" %}
        <h2>Contact Information</h2>
        <p>123 Main St.</p>
        <p>Anytown, USA 12345</p>
        <p>Phone: 000-1234</p>
    {% endif %}
{% endblock %}

In these examples, we use the {% block %} template tag to define a block of content that can be overridden in child templates.

We then use the {% if %} template tag to conditionally display content in each block based on the page the user is on.

The request.path variable contains the URL of the current page, so we use it to check if the user is on the home page, the products page, or the contact page.

As simple as that!

Best practices for using nested if else statements in Django templates

  1. Keep it simple: Keep nested if statements as simple as possible. Complex logic can quickly become difficult to understand and debug, so try to break down your code into smaller, more manageable nested branches.
  2. Use indentation: Use proper indentation to make your code more readable. Try to have 4 spaces to make your code scannable. It will help you to see how the nested if else statements are structured, and also makes it easier for others to read and understand.
  3. Avoid nesting your if statements too deep: In general, it’s best to limit nested if else statements to two or three levels deep. If you find yourself going deeper than this, it may be time to rethink your approach.
  4. Use logical operators where necessary: When using nested if else statements, it’s a good idea to use logical operators like “and” and “or” to simplify your code. This can make your code more efficient and easier to maintain.
  5. Optimize for performance: Avoid using unnecessary variables and try to minimize the number of times you access the database. This can help to ensure that your code is fast and efficient, even when dealing with complex logic.

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 *