MichaelRSF
MichaelRSF

Reputation: 896

Extends base template not appearing in Flask Python

I've got a base.html page that has both a header and a footer block. When I use {% extends "base.html" %} in my home.html page, I get nothing from the base.html page.

If I use {% include "base.html" %}, all my content in the home.html page is at the bottom, with the header and footer at the top. Does anyone know how I can fix this?

I'd like the header block at the top, the content from home.html in the middle, and the footer block rendered on the bottom of the home page. I'd be grateful for any help. Thanks.

Here is my code. myapp.py

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

@app.route("/")
@app.route("/home")
def home():


    return render_template("home.html", title="Home",
                          menu = menu)


@app.route("/base")
def base():

    return render_template("base.html", title="Base")

if __name__ == "__main__":
    app.run(debug=True)

base.html

<!DOCTYPE html>
<html>
    <head>
        <title>{{title}} - Restaurant</title>
</head>
<body>

    {% block header %}

 <ul>
     <li><a href="{{url_for('home')}}">Home</a></li>

    </ul>

    {% endblock header %}



    {% block footer %}

    <h1>This is a footer</h1>

    {% endblock footer %}

</body>

home.html

{% extends "base.html" %}
{% block header %}

<h1>Home Page</h1>

{% endblock header %}



{% block footer %}

<h1>New stuff in home page</h1>

{% endblock footer %}

Upvotes: 1

Views: 3265

Answers (2)

Gage
Gage

Reputation: 51

Try this?

base.html

<!DOCTYPE html>
<html>
<head>
        <title>{% block title %}{% endblock %} - Restaurant</title>
</head>
<body>

    {% block header %}

    <ul>
        <li><a href="">Home</a></li>
    </ul>

    {% endblock header %}

    {% block content %}{% endblock %}

    <h1>This is a footer</h1>

</body>

home.html

{% extends "base.html" %}
{% block content %}

{% block header %}

<h1>Home Page</h1>

{% endblock header %}


{% block footer %}

<h1>New stuff in home page</h1>

{% endblock footer %}

{% endblock %}

https://flask.palletsprojects.com/en/1.1.x/tutorial/templates/

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599530

Defining a block in a child template automatically overrides the version from the parent template completely. If you want to also output the parent version, you need to call super() - see the Jinja2 docs.

So your home.html should be:

{% extends "base.html" %}
{% block header %}
{{ super() }}
<h1>Home Page</h1>
{% endblock header %}


{% block footer %}
{{ super() }}
<h1>New stuff in home page</h1>
{% endblock footer %}

Upvotes: 3

Related Questions