Introduction
Flask is a micro web framework for Python that allows you to build web applications. One of its key features is the ability to use templates to generate dynamic web pages. In this guide, we'll explore how to work with templates in Flask, including creating templates, passing data to them, and rendering dynamic web pages.
Step 1: Creating Templates
Templates in Flask are typically created using HTML files with placeholders for dynamic content. Here's an example of a simple template named "index.html" that displays a variable:
<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>Hello, {{ username }}!</h1>
</body>
</html>
In this example, "{{ username }}" is a placeholder that will be replaced with dynamic data when the template is rendered.
Step 2: Passing Data to Templates
In your Flask application, you can pass data to templates using the `render_template` function. Here's an example of how to render the "index.html" template with a dynamic username:
from flask import Flask, render_template
app = Flask(__name)
@app.route('/')
def home():
username = 'John'
return render_template('index.html', username=username)
The "render_template" function takes the template name and any variables you want to pass to the template as keyword arguments.
Step 3: Rendering Dynamic Web Pages
When a user accesses your Flask route, the template is rendered with the provided data. Here's the result of rendering the "index.html" template with the dynamic username:
<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>Hello, John!</h1>
</body>
</html>
The placeholder "{{ username }}" has been replaced with the value "John" in the rendered web page.
Conclusion
Working with templates in Flask is a powerful way to create dynamic web pages. By following these steps, you can create templates, pass data to them, and render dynamic content for your web applications. This flexibility allows you to build rich, data-driven web pages in Flask with ease.