Why does the title appear in the body of the page when using Flask?

advertisements

Everything was working fine including the title until I went to add an icon in. Upon manually creating the <head> and calling {{ super() }} to bring in Bootstrap's black magic, the title now displays above the navigation bar.

base.html

{% extends "bootstrap/base.html" %}

{% block head %}
    {{ super() }}
    {% block title %}{% block page_name %}{% endblock %} - MyFlask{% endblock %}
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
{% endblock %}

<body>
    {% block navbar %}
        <nav class="navbar navbar-default">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#">MyFlask</a>
                </div>
            </div>
        </nav>
    {% endblock %}
</body>

index.html

{% extends "base.html" %}

{% block page_name%}Index{% endblock %}


When you use the super() function in a block, you are adding new contents to that block instead of replacing the original content. So when you called super() in the head block, Jinja2 inserted the head block's content from the bootstrap/base.html:

  <head>
    {%- block head %}
    <title>{% block title %}{% endblock title %}</title>

    {%- block metas %}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {%- endblock metas %}

    {%- block styles %}
    <!-- Bootstrap -->
    <link href="{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet">
    {%- endblock styles %}
    {%- endblock head %}
  </head>

After that you added a new title block, so now you have two of them, and that is the problem.

The solution is easy, don't define a new head block in base.html, just override the title block, and append your favicon lines to the styles:

{% extends "bootstrap/base.html" %}

{% block title %}{% block page_name %}{% endblock %} - MyFlask{% endblock %}

{%- block styles %}
{{ super() }}
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
{% endblock %}

{% block navbar %}
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">MyFlask</a>
            </div>
        </div>
    </nav>
{% endblock %}