Contents

Rendering Templates in Flask

Rendering templates is a powerful feature in Flask that allows you to create dynamic web pages by combining Python code with HTML. Flask uses the Jinja2 template engine to make this possible. Let’s dive into how you can create and render HTML templates, use template inheritance, and pass data from your Flask views to these templates.

Introduction to Jinja2 Template Engine

Jinja2 is the template engine that Flask uses to combine Python code with HTML. It allows you to write Python-like expressions inside your HTML files, making your web pages dynamic and responsive to data.

Here’s a quick example of what a Jinja2 template might look like:

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>


				
			

In this template:

  • {{ title }} and {{ name }} are placeholders for variables that you can pass from your Flask app.
  • Jinja2 will replace these placeholders with the actual values when rendering the template.

Creating and Rendering HTML Templates with Flask

To use templates in Flask, you need to create an HTML file and place it in a templates directory within your project. Let’s create a simple example.

Step 1: Set Up the Template Directory

In your project directory, create a templates folder. Inside this folder, create an HTML file called index.html:

				
					/your-project
  /templates
    index.html
  app.py


				
			

Step 2: Create a Basic Template

Here’s what your index.html might look like:

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
</head>
<body>
    <h1>Welcome to {{ name }}'s Website</h1>
    <p>This is a basic Flask template rendering example.</p>
</body>
</html>


				
			

Step 3: Render the Template in Flask

Now, you can render this template from your Flask view function in app.py:

				
					from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', title='Home Page', name='John Doe')

if __name__ == '__main__':
    app.run(debug=True)


				
			

In this example:

  • render_template('index.html', title='Home Page', name='John Doe') tells Flask to render index.html and replace {{ title }} with “Home Page” and {{ name }} with “John Doe”.
  • When you visit http://127.0.0.1:5000/, you’ll see your dynamic HTML page with the data you passed in.

Using Template Inheritance (Base Templates)

Template inheritance allows you to create a base template that other templates can extend. This is useful for maintaining consistency across multiple pages in your application.

Step 1: Create a Base Template

In your templates directory, create a new file called base.html:

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My Flask App{% endblock %}</title>
</head>
<body>
    <header>
        <h1>My Flask Application</h1>
    </header>

    <main>
        {% block content %}{% endblock %}
    </main>

    <footer>
        <p>&copy; 2024 My Flask App</p>
    </footer>
</body>
</html>


				
			

In this base template:

  • {% block title %}{% endblock %} and {% block content %}{% endblock %} are placeholders that can be overridden by other templates.

Step 2: Create a Child Template

Now, create another template called home.html that extends base.html:

				
					{% extends 'base.html' %}

{% block title %}Home{% endblock %}

{% block content %}
    <h2>Welcome to the Home Page!</h2>
    <p>This is the home page of our Flask app.</p>
{% endblock %}


				
			

Step 3: Render the Child Template in Flask

Modify your view function to render home.html:

				
					@app.route('/')
def home():
    return render_template('home.html')

				
			

When you visit the homepage, Flask will use base.html as the layout and insert the content from home.html into the appropriate blocks.

Passing Data from Flask Views to Templates

You can pass data from your Flask view functions to your templates using the render_template function. This data can then be accessed within your templates using Jinja2 syntax.

Example:

				
					@app.route('/profile/<username>')
def profile(username):
    user_info = {
        'name': username,
        'age': 30,
        'location': 'New York'
    }
    return render_template('profile.html', user=user_info)


				
			

In the profile.html template, you can access the user dictionary:

				
					{% extends 'base.html' %}

{% block title %}{{ user.name }}'s Profile{% endblock %}

{% block content %}
    <h2>{{ user.name }}</h2>
    <p>Age: {{ user.age }}</p>
    <p>Location: {{ user.location }}</p>
{% endblock %}

				
			

This will dynamically render a user’s profile page based on the data passed from the view function.

Summary

Rendering templates with Flask allows you to create dynamic, data-driven web pages. The Jinja2 template engine makes it easy to embed Python logic within your HTML, while template inheritance helps maintain a consistent layout across your application. By passing data from your Flask views to templates, you can create personalized and interactive user experiences.