Skip to content

Rendering Templates

Flask renders templates using render_template()render_template().

Step 1: create a template file

Create templates/home.htmltemplates/home.html:

<!doctype html>
<html>
  <head>
    <title>Home</title>
  </head>
  <body>
    <h1>Welcome to Flask</h1>
  </body>
</html>
<!doctype html>
<html>
  <head>
    <title>Home</title>
  </head>
  <body>
    <h1>Welcome to Flask</h1>
  </body>
</html>

Step 2: render it from a route

from flask import Flask, render_template
 
app = Flask(__name__)
 
 
@app.route("/")
def home():
    return render_template("home.html")
from flask import Flask, render_template
 
app = Flask(__name__)
 
 
@app.route("/")
def home():
    return render_template("home.html")

Flask will:

  • find templates/home.htmltemplates/home.html
  • render it (no variables yet)
  • return the HTML as an HTTP response

How template lookup works

Flask searches the templates folder relative to your app.

If you see:

  • TemplateNotFound: home.htmlTemplateNotFound: home.html

It usually means:

  • your templates folder is missing or incorrectly placed
  • your working directory is wrong
  • you’re using a package layout and need to confirm the path

πŸ§ͺ Try It Yourself

Exercise 1 – Create a Flask App

Exercise 2 – Dynamic Route

Exercise 3 – Return JSON

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did