Django framework logo

Django adding spaces and quotation marks when pushing string to templat

by: AWS November 09,2022 last update: 4 months, 1 week Django

Explain the problem

Environment :

  • Django: 2.1.1
  • OS: Linux

While working on a blog project, i was trying to set the title of the web pages to a dynamic value, i noticed that Django is adding spaces and quotation to the title of the page.

After investigating the issue, it turns out the problem is happening only when there is spaces between the blocks and the text which is meant for the title.

this is the title block of the base.html template.

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

 

And this is the block that uses the block.super( ) in post details template.

{% block title %}
    {{ post.title }} - {{ block.super }}
{% endblock %}

 

Result of the current implementation

To check how the browser is rendering the title tag with the current implementation 

Right click inside the web page and click inspect or just hit F12 in your keyboard

 

HTML title tag

Notice the quotes before and after the title and the spaces

The solution to fix the problem

This problem accures only when we add return lines inside the title block

so in order to fix it we need to remove those spaces like this:

This is base.html template

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

 

This is post_details.html template that inherit from the base template

{% block title %}
    {{ post.title }} - {{ block.super }}
{% endblock %}

 

After removing the spaces in the base.html title block, and inspecting the source code of the page

it truns out the spaces and the quotes are removed