Flask / Flask Templates and Jinja2

Template Basics

This tutorial will introduce you to the basics of working with templates in Flask. You will learn how to create and render templates using the Flask web framework and Jinja2.

Tutorial 1 of 4 4 resources in this section

Section overview

4 resources

Explains how to use Flask templates and Jinja2 for dynamic content rendering.

Introduction

The goal of this tutorial is to provide an introduction to working with templates in Flask using Jinja2, a modern and designer-friendly templating language for Python. This will give you the ability to build more dynamic and complex web applications.

By the end of this tutorial, you will learn:

  • How to define templates in Flask
  • How to render templates using Flask and Jinja2
  • How to use template inheritance in Jinja2

Prerequisites:
This tutorial assumes you have a basic understanding of Python and Flask. Familiarity with HTML is also beneficial.

Step-by-Step Guide

Flask and Jinja2

Flask uses the Jinja2 template engine to render templates. A template in Flask is simply a text file that can generate any text-based format like XML, CSV, HTML, etc.

To render a template you can use the render_template() method. This function takes the name of a template and a variable list of template arguments and returns the rendered template.

Template Inheritance

Jinja2 supports template inheritance, which allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.

Code Examples

Basic Template Rendering

Here is a simple example of how to define and render a template in Flask.

from flask import Flask, render_template
app = Flask(__name__)

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

In this example, home.html is the template file. Flask will look for templates in the templates folder in the same directory as your application.

Template with Variables

You can also pass variables to your templates. Here's an example where we pass a title variable to a template.

@app.route('/hello')
def hello():
    return render_template('hello.html', title='Hello Flask')

You can then use these variables in your template like this:

<h1>{{ title }}</h1>

Template Inheritance

Here is an example of how to use template inheritance in Jinja2. First, we define a base template.

<!-- base.html -->
<html>
  <head>
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    {% block body %}{% endblock %}
  </body>
</html>

Then, we define a child template that extends the base template.

<!-- home.html -->
{% extends "base.html" %}

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

{% block body %}
<h1>Welcome to my home page!</h1>
{% endblock %}

Summary

In this tutorial, we've covered the basics of working with templates in Flask using Jinja2. We have learned how to define and render templates, pass variables to templates, and use template inheritance.

For further learning, consider exploring how to use conditionals and loops in Jinja2 templates, as well as how to include and import templates.

Practice Exercises

  1. Exercise: Create a Flask application that renders a template with a list of names passed as a variable. The template should display each name in a separate line.

  2. Exercise: Create a Flask application with two routes. Each route should render a different template, but both templates should extend the same base template.

Solutions

  1. Solution:
@app.route('/names')
def names():
    names = ['Alice', 'Bob', 'Charlie']
    return render_template('names.html', names=names)
<!-- names.html -->
{% for name in names %}
<p>{{ name }}</p>
{% endfor %}
  1. Solution:
@app.route('/')
def home():
    return render_template('home.html')

@app.route('/about')
def about():
    return render_template('about.html')
<!-- base.html -->
<html>
  <head>
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    {% block body %}{% endblock %}
  </body>
</html>
<!-- home.html -->
{% extends "base.html" %}

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

{% block body %}
<h1>Welcome to my home page!</h1>
{% endblock %}
<!-- about.html -->
{% extends "base.html" %}

{% block title %}
About
{% endblock %}

{% block body %}
<h1>About me</h1>
{% endblock %}

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help