The Flask Templates Folder
The templates folder holds template files. The render_template call loads a file by name.
Write the template file
This code writes hello.html into the templates folder. The file holds the page with one blank.
import os
os.makedirs("templates", exist_ok=True)
with open("templates/hello.html", "w") as f:
f.write("<h1>Hello {{ name }}!</h1>")Render the file
The view loads hello.html by name and fills the blank with Ana.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("hello.html", name="Ana")Ask for the page
The test client asks for / and prints the page from the file.
client = app.test_client()
print(client.get("/").data.decode())Example
import os
os.makedirs("templates", exist_ok=True)
with open("templates/hello.html", "w") as f:
f.write("<h1>Hello {{ name }}!</h1>")
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("hello.html", name="Ana")
client = app.test_client()
print(client.get("/").data.decode())Key points
- Templates live in a folder named templates beside the app file.
- render_template("hello.html", name="Ana") loads hello.html.
- The file holds the HTML, and the view holds the values.
- Keep templates in files once pages grow.
In this example, hello.html is written into the templates folder first. The view loads the file by name with render_template and fills the blank with Ana. The test client asks for / and prints the filled-in page.
Note
Flask looks for templates beside the app file.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does render_template look for hello.html?