Home > Enterprise >  Python Flask not displaying contents with render_template()
Python Flask not displaying contents with render_template()

Time:09-27

When I try running my Flask program, all I see is the background color. No content from the HTML is displayed when I enter localhost:5000/index on browser.

My folder structure is like this:

Flask

---Test.py

---static

------styles

---------main.css

---templates

------base.html

------index.html

---pycache

Codes given below:

Test.py

from flask import Flask
from flask import render_template
from datetime import datetime

app = Flask(__name__)

@app.route("/")
@app.route("/index/")
def index():
    title = "Introduction to Python"
    now = datetime.now()
    fix = now.strftime("%m/%d/%Y, %H:%M:%S")
    return render_template("index.html", name=title, datetime=fix)

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

base.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ name }}</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/main.css') }}">
  </head>
  <body>
    <div id="container">
      <!-- Jinja directives: page contents will go between them -->
      {% block content %}
      {% endblock %}
    </div>
  </body>
</html>

index.html

{% extends 'base.html' %}
{% block body %}

<h1>{{ name }}</h1>

<h2>Current date and time: {{ datetime }}</h2>

{% endblock %}

main.css

body {
    font-family: 'Source Sans Pro', sans-serif;
    font-size: 100%;
    color: #000;
    background: #407189;
    margin: 0;
}

#container {
    margin: 2em auto;
    width: 740px;
    padding: 2em 4em;
    background: #f1f7dc;
}

h1, h2 {
    font-family: 'Droid Serif', serif;
    font-size: 3em;
    margin: 0;
                padding-bottom: 1em;
}

h2 {
    font-size: 2em;
}

p {
    font-size: 1.4em;
}

@media (max-width: 800px) {
    body {
        background: #f1f7dc;
    }
    #container {
        margin: 0;
        width: 100%;
        padding: 2em;
    }
}

CodePudding user response:

In base.html change {% block content %} to {% block body %}

    <div id="container">
      <!-- Jinja directives: page contents will go between them -->
      {% block body %}
      {% endblock %}
    </div>
  • Related