In this lesson, you'll learn how to use templates in Flask to create dynamic HTML pages. Templates allow you to separate your Python code from the HTML structure, making your web apps more organised and easier to maintain. You'll build on your knowledge from the previous lesson by adding templates to a Flask application. Here's what you'll do:
By the end, you'll understand how to generate dynamic web pages using Flask templates.
To start, create a dedicated folder for this lesson's project. This will keep your files organised.
FlaskTemplates
'. You can place it in your Documents folder or any preferred location.File > Open Folder
, then select the 'FlaskTemplates
' folder.FlaskTemplates
' as your workspace for this lesson.With your project folder ready, you're set to create a terminal in the next step.
Create a virtual environment to isolate your project's dependencies.
View > Command Palette
.Python: Create Environment
' and select it.Venv
' as the type.Python
version..venv
' folder in 'FlaskTemplates
'.Now, open a terminal in VS Code to run commands for setting up your environment.
View > Terminal
.pip install flask
Let's create a simple Flask app that we will build upon as we go through the lesson.
In VS Code, create a file named 'app.py
' in 'FlaskTemplates
'.
Add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to Flask Templates Lesson!'
Save the file.
Run python -m flask run
in the terminal.
Visit http://127.0.0.1:5000/ in your browser to see the message.
Stop the server with Ctrl+C
.