Making Websites with Flask/Templating
What is templating?Edit
When we are making Flask apps, we often want to return an HTML file, not just a string of HTML. Using templating, we can do this, along with many more advanced things like variables, loops, base templates, and more.
Making a Template FileEdit
To make a template file, we make an HTML file in a folder called templates
. For example, let's make called our HTML file index.html
and put the following in it:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Welcome to my Website!</h1>
<p>Hello world!</p>
</body>
</html>
Displaying TemplatesEdit
To display a template, we use the render_template()
function. To use it, we first of all need to import it from the Flask module:
from flask import render_template
Then, we use the render_template()
function when we are returning our functions. We pass in the name of the template HTML file into the render_template()
function. So, something like the following:
@app.route("/template")
def template_page():
return render_template("index.html")