Flask templates are a powerful way to separate the logic of your application from the presentation layer. In this tutorial, we'll go over the basics of using templates with Flask.
Templates Overview
Templates in Flask are HTML files that are used to generate dynamic web pages. They are placed in a folder named templates
in your Flask application directory.
Basic Structure
Here's a basic structure of a Flask template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My App{% endblock %}</title>
</head>
<body>
{% block content %}
<h1>Welcome to My App</h1>
{% endblock %}
</body>
</html>
Variables in Templates
You can pass variables to your templates using the render_template
function in Flask.
@app.route('/')
def index():
return render_template('index.html', title='Home', message='Welcome to the home page!')
In your template, you can access these variables using the {%
and %}
syntax:
<h1>{{ title }}</h1>
<p>{{ message }}</p>
Loops and Conditionals
You can use loops and conditionals in your templates to display dynamic content.
Loops
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Conditionals
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
Include Templates
You can include other templates within your main template using the {% include %}
tag.
{% include 'header.html' %}
Images
To include images in your templates, you can use the following syntax:
<img src="{{ url_for('static', filename='images/my_image.png') }}" alt="My Image">
Further Reading
For more information on Flask templates, check out the official Flask documentation.