Martin McBride, 2020-01-22
Tags template html

## Using HTML templates

Our current HTML page contains the complete home page - the HTML structure plus the actual text. What we will do now is convert the HTML page into a template, containing the HTML structure but with placeholders instead of the actual text. In that way, we can reuse the same HTML file for the home page, the about page, and any other pages which follow the same layout.

Here is the updated file. Take care to get the double curly brackets exactly right:

<html>
<body>
<h1>{{title}}</h1>
{{content}}
</body>
</html>


As you can see, we have replaced the actual title and content text with special placeholders {{title}} and {{content}}.

## Changing the Python code

How do we get our actual title and content to appear on the page? Well that is what render_template() does. Change the index() function in server.py like this:

@app.route('/')
def index():


As you can see, we have added two named parameters to the call, which supply values for the title and content. The render_template function takes the index.html file and substitutes each placeholder with the value of the parameter with the same name. So:

• {{title}} becomes 'Home page'
• {{content}} becomes 'My first Flask site'

Placeholders can be given any name you wish, provided you use the same name in the HTML and the function parameter. You must choose a name which is a valid Python variable name.

If you change the HTML and Python files and visit the page again in your browser, you will see that the page looks exactly the same as before - which is good.

To add an About page, we need to add a new routing function to our Python code - similar to the index() function but with different values. We will call the function about(), because it handles the About page:

@app.route('/about')


The differences between the about() function and the index() function are:

• The route is /about rather than /.
• The title and content parameters have different values.

It doesn't really matter what you call you routing functions, but is is best to choose consistent and meaningful names. So in this case the About page is handled by the about function.