Search code examples
pythonhtmlflaskfrontendweb-frontend

While using flask in python, I am not able to get the 'extend' feature to work properly


I'm new to programming. I decided to try to create a web app using flask, python, and HTML. I set up three files; two HTML and one python:

This is the HTML file that should have information replaced (didntwork.html):

<!doctype html>
<html>
  <head>
    <title>My Webpage</title>
  </head>
  <body>
      <h3>Information:</h3>
      {% block body %}{% endblock %}
  </body>
</html>
                                        .

This is the file that should input information to the first (connection.html):

{% extends 'didntwork.html' %}
{% block body %}
<h4>information content</h4>
{% endblock %}
                                        .

Finally, this is the logic for the flask app in python (main.py):

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('didntwork.html')


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

Unfortunately, the extends in the second HTML file does not seem to be recognized, and the information in its block will not be replaced in the first HTML file (didntwork.html).

This is the output:

This is the output.

The expected outcome should append an h4 tag to the body with the phrase 'information content'.

Any help would be appreciated, thanks.


Solution

  • The problem is the {% extends 'didntwork.html' %}. From what I can tell the file that contains this code:

    <!doctype html>
    <html>
      <head>
        <title>My Webpage</title>
      </head>
    <body>
      <h3>Information:</h3>
      {% block body %}{% endblock %}
    </body>
    </html>
    

    is your connection.html file.

    You are extending to the same file you're rendering (didntwork.html). You have to change the extends line to extend your base html, connection.html in this case.

    Use this code in your didntwork.html:

    {% extends 'connection.html' %}
    {% block body %}
    <h4>information content</h4>
    {% endblock %}
    

    You can find more information in Template Inheritance

    UPDATE BASE ON CLARIFICATION

    You're rendering the wrong file in your route. You should render the connection.html and this will extends your didntwork.html file.