djangodjango-templates

How can I use if else statements with multiple blocks in Django templates?


I want to load different meta tags based on the context data I receive.

As you can see, in case 1, I retrieve the name from '2. name', while in case 2, it comes from 'name'. When I use this if-else statement, I encounter an error stating that the use of multiple blocks is not allowed.

{% extends 'base.html' %}
{% load static %}
{% load custom_filters %}

{% if context.api_name == 'case 1' %}
    {% block meta_keywords %}
        <meta name="keywords" content="some keywords">
    {% endblock %}
    {% block meta_description %}
        <meta name="description" content="{{ context.json_data | get_key:'2. name' |default:'Unknown' }}">
    {% endblock %}

{% elif context.api_name == "case 2" %}
    {% block meta_keywords %}
        <meta name="keywords" content="some keywords">
    {% endblock %}

    {% block meta_description %}
        <meta name="description" content="{{ context.json_data | get_key:'name' |default:'Unknown' }}">
    {% endblock %}
{% endif %} 


TemplateSyntaxError
django.template.exceptions.TemplateSyntaxError: 'block' tag
with name 'meta_keywords' appears more than once

Solution

  • Try turning the logic around, like:

    {% block meta_keywords %}
    
        {% if context.api_name == 'case 1' %}
            <meta name="keywords" content="some keywords">
        {% elif context.api_name == "case 2" %}
            <meta name="keywords" content="some keywords">
        {% endif %} 
    
    {% endblock %}
    
    {% block meta_description %}
    
        {% if context.api_name == 'case 1' %}
            <meta name="description" content="{{ context.json_data | get_key:'2. name' |default:'Unknown' }}">
        {% elif context.api_name == "case 2" %}
            <meta name="description" content="{{ context.json_data | get_key:'name' |default:'Unknown' }}">
        {% endif %} 
    
    {% endblock %}
    

    I'm guessing that content="some keywords" will be different in each case.