Ali Zain
Ali Zain

Reputation: 41

How to conditionally modify the <title> tag in Django templates?

I have a base template (main.html) with the following code for the tag:

main.html:

<title>{% block title %}{% endblock %} | Application</title>

In a child template (dashboard.html), I override the title block like this:

dashboard.html:

{% extends 'main.html' %}
{% block title %}Dashboard{% endblock %}

If the title block is not overridden in the child template, I want the title to just be Application, without the extra | Application. How can I check if the block is overridden and modify the title accordingly?

When I pass the title block from the child template like this:

{% extends 'main.html' %}
{% block title %}Dashboard{% endblock %}

Then I need the title to display as "Dashboard | Application".

If I don't pass the title block:

{% extends 'main.html' %}

Then the title should just be "Application".

Upvotes: 1

Views: 71

Answers (1)

Selcuk
Selcuk

Reputation: 59425

You can't do that in plain Django, but you can work around it by changing your main block to

<title>{% block title %}{% endblock %}Application</title>

and overriding it like

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

Alternatively, you can use the {% include %} tag instead of {% block %}:

title.html:

<title>{% if title %}{{ title }} | {% endif %}Application<title>

then

dashboard.html::

{% include "title.html" with title="Dashboard" %}

Upvotes: 2

Related Questions