M SH M SH - 2 months ago 13
Python Question

Jinja2 include & extends not working as expected

I used

include
and
extends
in the
base.html
file and expect them to be included in order. But the
extends
template is appended to the end of the file.

I expect my template to give me the output of:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Test String from block !</p>
<footer>text from footer.</footer>
</body>
</html>


but the current result are:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<footer>text from footer.</footer>
</body>
</html>
<p>Test String from block !</p>


In
base.html
, first I include
header.html
, then
content.html
and then
footer.html
but the rendered order is
header.html
,
footer.html
,
content.html
.

index.html


{% extends "base.html" %}
{% block content %}
<p>Test String from block !</p>
{% endblock %}


base.html


{% include "header.html" %}
<body>
{% extends "content.html" %}
{% include "footer.html" %}


header.html


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>


content.html


{% block content %}

{% endblock %}


footer.html


<footer>text from footer.</footer>
</body>
</html>

Answer

I would suggest structuring slightly differently. I used a structure like this just recently and got the proper results.

index.html:

{% extends "base.html" %}

{% block head %}
    <!-- if you want to change the <head> somehow, you can do that here -->
{% endblock head %}

{% block content %}
<body>
    <p>Test String from block !</p>
    {% include 'content.html' %}
</body>
{% include 'footer.html' %}
{% endblock content %}

base.html:

<!DOCTYPE html>
    <html lang="en">
    <head>
        {% block head %}
        <meta charset="UTF-8">
        <title>Title</title>
        {% endblock head %}
    </head>
    {% block content %}
    {% endblock content %}
</html>

content.html:

<!-- whatever you want in here -->

footer.html:

<footer>text from footer.</footer>

Hopefully that helps.