templates - pkirlin/lab-flask GitHub Wiki

Templates

It is a big pain to write HTML code and Python code in the same file. This is especially tiresome when the HTML code a route needs to return gets really long. You can see it's already a pain in the previous lesson. Flask has an easy solution, called templates, that lets us separate most of the HTML code into separate files from the Python application code.

Making a HTML template

  • Go into the "templates" folder in replit. You will find this folder along the left-hand bar where all the files are displayed. You can click on the folder itself, and then click "add a file" underneath "templates."
  • Create a new file inside called time.html. This file must be saved in your templates directory. Add the following code:
<html>
    <head>
        <title>Time</title>
    </head>
    <body>
        <h1>What time is it?</h1>
        The current time is {{ timestring }}.
    </body>
</html>
  • In main.py, change your import Flask line to from flask import Flask, render_template.

  • Remove the "return" statement from your "time" route, and replace it with the following line:

    return render_template("time.html", timestring=timestring)
  • Save and reload the time webpage.

How does this work?

  • Let's examine the HTML template first.

  • The HTML templates is literally just HTML code. You can put any HTML code in an HTML template. You can also put variables in an HTML template, surrounded by double sets of curly braces. Variables are not part of HTML; they are a concept that the Flask template engine uses.

  • Now let's examine the Python code.

  • There is not much difference in the previous time route and the new one. We have imported the render_template function, which we use to tell Flask that we want to use an HTML template, rather than return raw HTML code ourselves. render_template reads in the HTML file specified, in this case time.html (which it looks for in the templates directory, hence why we had to put the file there) and replaces all the variables in the HTML with the Python values for those variables that you passed to the function.

  • The syntax for passing Python values or variables to the HTML template uses something called keyword arguments. This syntax is actually a part of Python, though we don't use it in CS141. Normally, we call functions using positional arguments, which means the parameter variables in the called function are assigned left-to-right from the values given in the calling function. Python allows you to add keyword arguments to send extra information to a function. In the template engine, we use the syntax variable=value, which creates a variable in the HTML template with the specified name, and the value of this variable will be the specified value. You can use literal values, Python variables, or arbitrary expressions as the values.

  • Note: The names of the HTML variables and the Python variables do not have to be the same! In this case they are, which is why we used the syntax timestring=timestring. If we wanted to, we could have said timestring="three thirty" or timestring=a + b, provided a and b were string variables we could concatenate.

You try it

  • Create a new HTML template called random.html that will display a randomly generated number. The template should contain some HTML like time.html does, along with some text like "Your random number is" followed by a template called {{ number }}.
  • Add a new route to your Flask app called /random_number) linked to a Python function called random_number() (don't call it random() because that's the built-in function for generating random numbers that we will need in a minute!). Write code in this route that will use the random.html HTML template to display a random number between 1 and 10. You will need to import random in your Python code and then call random.randint(1, 10) inside your random_number() function, then send the newly-generated random number to the HTML template. Reload the page a few times to see different random numbers each time!
  • Every time you change the python/html code, you will need to stop and re-run the Flask app (big green button).
  • Scroll down for the answer if you get stuck: (TRY IT YOURSELF FIRST!!!)

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

<html>
    <head>
        <title>Random numbers</title>
    </head>
    <body>
        <h1>Random number generator</h1>
        The random number is {{ number }}.
    </body>
</html>
@app.route("/random_number")
def random_number():
    n = random.randint(1, 10)
    return render_template("random.html", number=n)
⚠️ **GitHub.com Fallback** ⚠️