M SH M SH - 2 months ago 9
Python Question

flask jinja2 include & exclude not working as expected

today i was working with flask.i used include and extends in my

base.html
file and i expect them to be included in order.but the extend html codes are appended to the end of the file after
</html>
tag.

here is a simplified version on my template here.i cant change/merge files.
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>


as you can see in
base.html
,first i include
header.html
,then
content.html
and then
footer.html
but the rendered is :
header.html
,
footer.html
,
content.html
.

what am i doing wrong here?
(also,please tell me how i can ask better questions or improve my questions quality,this is the first time i use stackoverflow)

app.py:

from flask import Flask,render_template
app = Flask(__name__)

@app.route("/")
def home():
return render_template("index.html")

app.run()


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.