[Python] How to check if a Django template block is overridden in the child template?

Discussão em 'Python' iniciado por Stack, Fevereiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on a Django project where I have a base layout template (main.html) and a child template (dashboard.html).

    I want to modify the tag so that if the child template provides a title, it should be formatted as: Page Title | Application

    Otherwise, if the block is empty or not overridden, it should just be: Application (without the extra | Application).

    Here’s my main.html:

    {% load static %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
    {% block title %}{% endblock %}{% if block.super %} | Application{% endif %}
    </title>
    <link rel="stylesheet" href="{% static 'assets/css/style.css' %}">
    </head>
    <body>
    {% block content %}{% endblock %}
    </body>
    </html>


    And here’s my dashboard.html:

    {% extends 'core/layouts/main.html' %}

    {% block title %}Dashboard{% endblock %}

    {% block content %}
    <h2>Welcome, {{ user.name }}</h2>
    <a href="{% url 'logout' %}">Logout</a>
    {% endblock %}


    Issue: When the child template doesn't override the title block, the output is:

    | Application


    Instead of just:

    Application


    How can I check whether a block is overridden in the child template and adjust the title accordingly?

    Would appreciate any suggestions. Thanks!

    Continue reading...

Compartilhe esta Página