Creating templates
Flask is a powerful micro-framework that is widely used in web application development. One of the key features Flask offers is the use of templates, which allows you to generate dynamic HTML content. In this tutorial, we will guide you through creating templates in Flask.
What are Templates?
In the context of web development, templates are HTML files where you can embed Python codes. They are used to generate dynamic web pages. What makes templates efficient is that you can use the same base layout for multiple pages in your web application.
Jinja2
Flask uses a template engine called Jinja2 to handle templates. Jinja2 allows you to implement conditions, loops, and filters in your HTML files, which enhances the dynamism and reusability of your templates.
Setting Up Your Project
Before we start creating templates, make sure you have Flask installed in your project. If not, install it using pip:
pip install flask
After installing Flask, create a new file named main.py
and add the following code:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
if __name__ == "__main__":
app.run(debug=True)
In the above code, we've imported the render_template
function from the flask module. We'll use this function to render our HTML templates.
Creating Your First Template
By default, Flask looks for templates in a directory named templates
in your project root directory.
Let's create a new directory named templates
and inside this directory, create a new file named home.html
.
Add the following HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Welcome Home!</title>
</head>
<body>
<h1>Welcome to our Flask tutorial!</h1>
</body>
</html>
Now, if you run your Flask application and visit http://localhost:5000/
, you should see the message "Welcome to our Flask tutorial!"
Using Variables in Templates
One of the great things about Jinja2 is that it allows us to use variables in our templates. Let's modify our home()
function to pass a variable to our template:
@app.route('/')
def home():
welcome_message = "Welcome to our Flask tutorial!"
return render_template('home.html', message=welcome_message)
We can then use this variable in our home.html
template:
<body>
<h1>{{ message }}</h1>
</body>
Now, if you refresh your page, you should see the same message as before. But this time, the message is coming from a Python variable!
Conclusion
In this tutorial, we've learned how to create a basic template in Flask and how to use variables in our templates. There's a lot more you can do with Flask templates, such as using conditions, loops, and filters, which we'll cover in the next tutorials. Remember, templates are a powerful tool to generate dynamic content and make your web application more efficient. Happy Coding!