This document provides an overview of how to use templates in Flask applications. Templates are used to render HTML content dynamically.
Features
- Dynamic Rendering: Templates allow you to render HTML content based on the data provided by your Flask application.
- Separation of Concerns: Templates help separate the presentation logic from the business logic, making your code cleaner and more maintainable.
- Extensibility: You can easily extend and customize templates as your application grows.
Basic Usage
To use templates in Flask, you need to follow these steps:
- Create a Templates Folder: Create a folder named
templates
in your Flask application directory. - Create a Template File: Inside the
templates
folder, create an HTML file with a.html
extension. - Render the Template: Use the
render_template
function in your Flask view to render the template.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
Template Syntax
Flask templates use a simple syntax to render data into HTML. Here are some common syntaxes:
- Variable: To render a variable, use the
{{ variable_name }}
syntax. - List: To render a list, use the
{{ list_variable }}.index()
syntax. - Conditional: To render content conditionally, use the
{% if condition %}
and{% endif %}
tags. - For Loop: To render a loop, use the
{% for item in list %}
and{% endfor %}
tags.
Example
Here's an example of a simple template that displays a welcome message:
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, {{ name }}!</h1>
</body>
</html>
To render this template, you can pass a name
variable to the render_template
function:
@app.route('/')
def index():
return render_template('index.html', name='John Doe')
Further Reading
For more information on Flask templates, please refer to the official Flask documentation.
Flask Template