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>
        <title>My Website</title>
        <h1>Welcome to my Website!</h1>
        <p>Hello world!</p>

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:

def template_page():
    return render_template("index.html")

Using Python Variables in TemplatesEdit

For and While LoopsEdit

Creating a Base TemplateEdit

Changing the Templates FolderEdit