25% developed

Making Websites with Flask/Templating

From Wikibooks, open books for an open world
Jump to navigation Jump to search

What is templating?[edit | edit source]

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 File[edit | edit source]

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 Templates[edit | edit source]

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")

Using Python Variables in Templates[edit | edit source]

For and While Loops[edit | edit source]

Creating a Base Template[edit | edit source]

Changing the Templates Folder[edit | edit source]