Making Websites with Flask/Templating
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")
Inline Code Storing
[edit | edit source]Another way you can serve HTML code is by serving it inline. Here is a example:
from flask import *
app = Flask(__name__)
@app.route('/')
def inline_example();
return """
<!DOCTYPE html><html>
<head>
<title>My Inline Code Example</title>
</head>
<body>
<h1>You did it</h1>
Good Job!
</body>
</html>
"""
if __name__ == "__main__":
app.run(debug=true)
In this example, instead of the HTML being loaded from an external file, it is being directly given to the user.
Test it out
[edit | edit source]On your Python editor, run the program. Then open a browser. Navigate to http://127.0.0.1:5000/ and you should see a web page congratulating you. If you don't, check the console to debug.