1

I want to serve .HTML files that link to a styles.CSS file using <link rel='stylesheet'> in my web-app using render_template() function in Flask. It will run as a local-app using FlaskWebGUI library in Python.

File structure:

flaskGUI ---
      templates ---
             index.html
             styles.css
      flaskapp.py

flaskapp.py code:

from flask import Flask, render_template
from flaskwebgui import FlaskUI

app = Flask(__name__)
ui = FlaskUI(app)

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


ui.run()

index.html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index</title>
</head>

<body>
    <h1>Index</h1>
    <p>This is an HTML file served up by Flask</p>
</body>

</html>

styles.css code:

body {
  background-color: powderblue;
}
h1 {
  color: blue;
}
p {
  color: red;
}

Expected: Powder-blue background, Blue 'Index' text, red paragraph text.

Actual Result: White background, black text.

dodiameer
  • 51
  • 1
  • 7

1 Answers1

2

The standard way to serve static files is to put them in the static folder, not the templates folder, then use url_for('static', filename='styles.css') to link to it.

Alternatively, use send_from_directory to serve it with a custom route.

@app.route("/styles.css")
def styles():
    return send_from_directory("templates", "styles.css")
davidism
  • 121,510
  • 29
  • 395
  • 339
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424