Python course Β· Module 5: Flask and Web Apps

Jinja2 Templates - dynamic interfaces

12 min read Β·
In this lesson11

Welcome back! Darwin here with a new tool - Jinja2 templates!

So far you've been writing HTML as hardcoded strings in Python functions. That works, but it's unreadable, hard to maintain, and impractical for larger applications!

Safari Analogy: Hardcoded HTML is like drawing every safari map by hand from scratch - tiring and time-consuming! Jinja2 templates are like map templates - you prepare the structure once, then just fill in the data!

The problem with hardcoded HTML

Remember the code from the previous lesson:

@app.route('/species')
def list_species():
    species_html = ""
    for spec in species_db.values():
        species_html += f"""
        <div style="background: white; padding: 15px;">
            <h3>{spec['name']}</h3>
            <p><strong>Population:</strong> {spec['population']}</p>
        </div>
        """

    return f"""
    <!DOCTYPE html>
    <html>
    <head><title>Species list</title></head>
    <body>
        <h1>Species list</h1>
        {species_html}
    </body>
    </html>
    """

Problems: HTML mixed with Python logic Hard to read and edit No HTML syntax highlighting Code duplication (navigation, footer) Difficult collaboration with designers No reusability

Solution - Jinja2 Templates

Jinja2 is a template engine - a templating engine that allows separating HTML from Python logic.

How it works?

  1. You create HTML files in the templates/ folder
  2. You use {{ variable }} to display data
  3. You use {% if %}, {% for %} for logic
  4. Flask renders template + data β†’ finished HTML

Analogy: Jinja2 is like a fill-in form - you have a ready structure (HTML), you just insert data (Python variables)!

Project structure with templates

safari_web/
β”‚
β”œβ”€β”€ app.py
β”‚
β”œβ”€β”€ templates/          ← Folder for HTML templates
β”‚   β”œβ”€β”€ base.html
β”‚   β”œβ”€β”€ home.html
β”‚   β”œβ”€β”€ species_list.html
β”‚   └── species_detail.html
β”‚
└── static/             ← Folder for static files
    β”œβ”€β”€ css/
    β”‚   └── style.css
    β”œβ”€β”€ js/
    β”‚   └── script.js
    └── images/
        └── logo.png

Flask automatically looks for files in the templates/ folder!

Jinja2 basics - syntax

1. Variables - {{ }}

Display the value of a variable:

<h1>{{ species_name }}</h1>
<p>Population: {{ population }}</p>

2. Expressions

<p>{{ 2 + 3 }}</p>                    <!-- 5 -->
<p>{{ "Hello " + name }}</p>          <!-- Hello Darwin -->
<p>{{ species.name }}</p>             <!-- Attribute access -->
<p>{{ species['name'] }}</p>          <!-- Dict access -->
<p>{{ species_list[0] }}</p>          <!-- List element access -->

3. Control structures - {% %}

If statement:

{% if population > 1000 %}
    <span style="color: green;">Safe</span>
{% elif population > 100 %}
    <span style="color: orange;">Endangered</span>
{% else %}
    <span style="color: red;">Critically endangered</span>
{% endif %}

For loop:

<ul>
{% for species in species_list %}
    <li>{{ species.name }} - {{ species.population }} individuals</li>
{% endfor %}
</ul>

For loop with index:

{% for species in species_list %}
    <p>{{ loop.index }}. {{ species.name }}</p>
{% endfor %}

4. Filters - |

Filters modify variables:

<p>{{ name | upper }}</p>                    <!-- LION -->
<p>{{ name | lower }}</p>                    <!-- lion -->
<p>{{ name | title }}</p>                    <!-- Lion -->
<p>{{ species_list | length }}</p>           <!-- 3 -->
<p>{{ price | round(2) }}</p>                <!-- 19.99 -->
<p>{{ text | truncate(50) }}</p>             <!-- Truncate to 50 chars -->
<p>{{ published_date | default('None') }}</p> <!-- Default value -->

Popular filters:

  • upper, lower, title - case change
  • length - list/string length
  • default(value) - default value if None
  • round(n) - round to n places
  • truncate(n) - truncate text
  • join(separator) - join list
  • safe - disable HTML escaping (use carefully!)

5. Comments - {# #}

{# This is a comment - won't be visible in HTML #}
<h1>{{ species_name }}</h1>

Rendering templates in Flask

Use the render_template() function:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    # Render template + pass variables
    return render_template('home.html',
                         title='Safari Database',
                         species_count=3)

@app.route('/species/<int:species_id>')
def show_species(species_id):
    species = species_db.get(species_id)

    return render_template('species_detail.html',
                         species=species)

Flask:

  1. Looks for the file templates/home.html
  2. Renders the template with passed variables
  3. Returns finished HTML

First template - home.html

Create a templates/ folder and a home.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f4f1de;
        }
        h1 { color: #2c5f2d; }
    </style>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>Welcome to Safari Database!</p>
    <p>The database contains <strong>{{ species_count }} species</strong>.</p>
</body>
</html>

app.py:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html',
                         title='Safari Database',
                         species_count=3)

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

Run: http://localhost:5000/ - you'll see the rendered template!

Template inheritance

The most important Jinja2 feature! It allows creating a base template (layout) and extending it in other templates.

Analogy: Template inheritance is like DNA inheritance - a descendant species (child template) inherits traits from its parent (base template), but can have its own unique characteristics!

base.html - base template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Safari Database{% endblock %}</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f4f1de;
        }
        header {
            background-color: #2c5f2d;
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        nav {
            margin: 20px 0;
            padding: 15px;
            background: white;
            border-radius: 8px;
        }
        nav a {
            margin-right: 15px;
            color: #2c5f2d;
            text-decoration: none;
            font-weight: bold;
        }
        nav a:hover {
            text-decoration: underline;
        }
        main {
            background: white;
            padding: 30px;
            border-radius: 12px;
        }
        footer {
            margin-top: 30px;
            text-align: center;
            color: #666;
        }
    </style>
    {% block extra_css %}{% endblock %}
</head>
<body>
    <header>
        <h1>Safari Database</h1>
        <p>African species data management system</p>
    </header>

    <nav>
        <a href="{{ url_for('home') }}">Home</a>
        <a href="{{ url_for('list_species') }}">Species list</a>
        <a href="{{ url_for('search') }}">Search</a>
    </nav>

    <main>
        {% block content %}
        <!-- Content from child templates goes here -->
        {% endblock %}
    </main>

    <footer>
        <p>&copy; 2024 Safari Database by Darwin</p>
    </footer>

    {% block extra_js %}{% endblock %}
</body>
</html>

Blocks ({% block %}): Places that can be overridden in child templates.

home.html - extending base.html

{% extends 'base.html' %}

{% block title %}Home - Safari Database{% endblock %}

{% block content %}
    <h2>Welcome to Safari Database!</h2>
    <p>The database contains <strong>{{ species_count }} species</strong>.</p>

    <div style="margin-top: 30px;">
        <h3>System features:</h3>
        <ul>
            <li>Browse species list</li>
            <li>Search species</li>
            <li>Population statistics</li>
            <li>Add new observations</li>
        </ul>
    </div>

    <p style="margin-top: 30px;">
        <a href="{{ url_for('list_species') }}" style="background: #2c5f2d; color: white; padding: 10px 20px; border-radius: 4px; text-decoration: none;">
            See all species β†’
        </a>
    </p>
{% endblock %}

{% extends 'base.html' %} - inherits from base.html {% block content %} - overrides the content block

species_list.html - species list

{% extends 'base.html' %}

{% block title %}Species list - Safari Database{% endblock %}

{% block content %}
    <h2>All species ({{ species | length }})</h2>

    {% if species %}
        {% for spec in species %}
            <div style="background: #f9f9f9; padding: 20px; margin: 15px 0; border-radius: 8px; border-left: 4px solid #2c5f2d;">
                <h3 style="margin-top: 0;">{{ spec.name }}</h3>
                <p><strong>Scientific name:</strong> <em>{{ spec.scientific_name }}</em></p>
                <p><strong>Population:</strong> {{ spec.population }} individuals</p>

                {% if spec.population > 1000 %}
                    <span style="color: green;">Safe</span>
                {% elif spec.population > 100 %}
                    <span style="color: orange;">Endangered</span>
                {% else %}
                    <span style="color: red;">Critically endangered</span>
                {% endif %}

                <p style="margin-top: 15px;">
                    <a href="{{ url_for('show_species', species_id=spec.id) }}" style="color: #2c5f2d; font-weight: bold;">
                        See details β†’
                    </a>
                </p>
            </div>
        {% endfor %}
    {% else %}
        <p style="color: #666;">No species in the database.</p>
    {% endif %}
{% endblock %}

species_detail.html - species details

{% extends 'base.html' %}

{% block title %}{{ species.name }} - Safari Database{% endblock %}

{% block content %}
    {% if species %}
        <h2>{{ species.name }}</h2>

        <div style="background: #f9f9f9; padding: 30px; border-radius: 12px; border: 3px solid #2c5f2d;">
            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <td style="padding: 10px; font-weight: bold;">Common name:</td>
                    <td style="padding: 10px;">{{ species.name }}</td>
                </tr>
                <tr>
                    <td style="padding: 10px; font-weight: bold;">Scientific name:</td>
                    <td style="padding: 10px;"><em>{{ species.scientific_name }}</em></td>
                </tr>
                <tr>
                    <td style="padding: 10px; font-weight: bold;">Population:</td>
                    <td style="padding: 10px;">{{ species.population }} individuals</td>
                </tr>
                <tr>
                    <td style="padding: 10px; font-weight: bold;">Status:</td>
                    <td style="padding: 10px;">
                        {% if species.population > 1000 %}
                            <span style="color: green;">Safe</span>
                        {% elif species.population > 100 %}
                            <span style="color: orange;">Endangered</span>
                        {% else %}
                            <span style="color: red;">Critically endangered</span>
                        {% endif %}
                    </td>
                </tr>
                <tr>
                    <td style="padding: 10px; font-weight: bold;">System ID:</td>
                    <td style="padding: 10px;">{{ species.id }}</td>
                </tr>
            </table>
        </div>

        <p style="margin-top: 30px;">
            <a href="{{ url_for('list_species') }}" style="color: #2c5f2d;">← Back to list</a> |
            <a href="{{ url_for('home') }}" style="color: #2c5f2d;">← Home page</a>
        </p>
    {% else %}
        <h2>Species not found</h2>
        <p>The species with the given ID does not exist in the database.</p>
        <p><a href="{{ url_for('list_species') }}">← Back to list</a></p>
    {% endif %}
{% endblock %}

Static files

CSS, JavaScript, images files are stored in the static/ folder.

Structure:

static/
β”œβ”€β”€ css/
β”‚   └── style.css
β”œβ”€β”€ js/
β”‚   └── script.js
└── images/
    └── logo.png

static/css/style.css

/* Safari Database Styles */
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f4f1de;
}

header {
    background: linear-gradient(135deg, #2c5f2d 0%, #45a049 100%);
    color: white;
    padding: 30px;
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.species-card {
    background: white;
    padding: 20px;
    margin: 15px 0;
    border-radius: 8px;
    border-left: 4px solid #2c5f2d;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    transition: transform 0.2s;
}

.species-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 13px;
    font-weight: bold;
}

.badge-safe { background: #4caf50; color: white; }
.badge-endangered { background: #ff9800; color: white; }
.badge-critical { background: #f44336; color: white; }

Using static files in templates

<!DOCTYPE html>
<html>
<head>
    <title>Safari Database</title>
    <!-- Link to CSS -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <!-- Logo -->
    <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">

    <!-- Page content -->

    <!-- Link to JS -->
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>

url_for('static', filename='...') generates the URL to a static file.

Complete application with templates

app.py

# app.py
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# Test data
species_db = {
    1: {"id": 1, "name": "Lion", "scientific_name": "Panthera leo", "population": 120},
    2: {"id": 2, "name": "African Elephant", "scientific_name": "Loxodonta africana", "population": 450},
    3: {"id": 3, "name": "Cheetah", "scientific_name": "Acinonyx jubatus", "population": 7100},
    4: {"id": 4, "name": "Giraffe", "scientific_name": "Giraffa camelopardalis", "population": 850},
}
next_id = 5

@app.route('/')
def home():
    return render_template('home.html',
                         species_count=len(species_db))

@app.route('/species')
def list_species():
    return render_template('species_list.html',
                         species=list(species_db.values()))

@app.route('/species/<int:species_id>')
def show_species(species_id):
    species = species_db.get(species_id)
    return render_template('species_detail.html',
                         species=species)

@app.route('/search')
def search():
    query = request.args.get('q', '').lower()

    if query:
        results = [s for s in species_db.values()
                  if query in s['name'].lower() or query in s['scientific_name'].lower()]
    else:
        results = []

    return render_template('search.html',
                         query=query,
                         results=results)

if __name__ == '__main__':
    print("Safari Database starting...")
    app.run(debug=True)

templates/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 %}Safari Database{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    {% block extra_css %}{% endblock %}
</head>
<body>
    <header>
        <h1>Safari Database</h1>
        <p>African species data management system</p>
    </header>

    <nav>
        <a href="{{ url_for('home') }}">Home</a>
        <a href="{{ url_for('list_species') }}">Species list</a>
        <a href="{{ url_for('search') }}">Search</a>
    </nav>

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

    <footer>
        <p>&copy; 2024 Safari Database by Darwin | Powered by Flask & Jinja2</p>
    </footer>

    {% block extra_js %}{% endblock %}
</body>
</html>

templates/search.html

{% extends 'base.html' %}

{% block title %}Search - Safari Database{% endblock %}

{% block content %}
    <h2>Species search</h2>

    <form method="GET" style="margin: 30px 0;">
        <input type="text"
               name="q"
               value="{{ query }}"
               placeholder="Enter species name..."
               style="padding: 12px; width: 60%; border: 2px solid #2c5f2d; border-radius: 4px; font-size: 16px;">
        <button type="submit"
                style="padding: 12px 24px; background: #2c5f2d; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer;">
            Search
        </button>
    </form>

    {% if query %}
        <h3>Results for: "{{ query }}" ({{ results | length }})</h3>

        {% if results %}
            {% for species in results %}
                <div class="species-card">
                    <h3 style="margin-top: 0;">{{ species.name }}</h3>
                    <p><em>{{ species.scientific_name }}</em></p>
                    <p>Population: {{ species.population }} individuals</p>
                    <a href="{{ url_for('show_species', species_id=species.id) }}" style="color: #2c5f2d; font-weight: bold;">
                        See details β†’
                    </a>
                </div>
            {% endfor %}
        {% else %}
            <p style="color: #666; text-align: center; padding: 40px;">
                No species found matching query "{{ query }}"
            </p>
        {% endif %}
    {% else %}
        <p style="color: #666; text-align: center; padding: 40px;">
            Enter a species name to start searching.
        </p>
    {% endif %}
{% endblock %}

Useful Jinja2 techniques

1. Passing multiple variables

@app.route('/dashboard')
def dashboard():
    return render_template('dashboard.html',
                         title='Dashboard',
                         user='Darwin',
                         species_count=10,
                         observations_count=152,
                         recent_activity=['Lion observation', 'Added cheetah'])

2. Passing a dictionary as **kwargs

context = {
    'title': 'Dashboard',
    'user': 'Darwin',
    'species_count': 10
}

return render_template('dashboard.html', **context)

3. Global variables (available in all templates)

@app.context_processor
def inject_globals():
    return {
        'app_name': 'Safari Database',
        'version': '1.0.0',
        'current_year': 2024
    }

# Now {{ app_name }}, {{ version }}, {{ current_year }} work everywhere!

4. Custom filters

@app.template_filter('format_population')
def format_population(value):
    if value >= 1000:
        return f"{value / 1000:.1f}k"
    return str(value)

# In template:
# {{ species.population | format_population }}  β†’ "7.1k"

5. Macros (reusable components)

{# macros.html #}
{% macro render_species_card(species) %}
    <div class="species-card">
        <h3>{{ species.name }}</h3>
        <p><em>{{ species.scientific_name }}</em></p>
        <p>Population: {{ species.population }}</p>
    </div>
{% endmacro %}

{# In other templates #}
{% from 'macros.html' import render_species_card %}

{% for species in species_list %}
    {{ render_species_card(species) }}
{% endfor %}

Summary

In this lesson you learned:

  • Why templates are better than hardcoded HTML
  • Jinja2 syntax ({{ }}, {% %}, {# #})
  • Variables and expressions
  • Control structures (if, for)
  • Filters (|upper, |length, |default)
  • Template inheritance (extends, blocks)
  • Static files (CSS, JS, images)
  • url_for() in templates
  • Complete Safari Database application with templates

Final Safari Analogy: Jinja2 templates are like genetic DNA templates - you have a base structure (base.html = ancestor DNA), which you extend in descendants (child templates = descendant DNA) with unique characteristics (blocks)! All species (templates) inherit common traits (navigation, footer), but have their own uniqueness (content)!

Next lesson: Darwin will show you Flask-WTF - forms and data validation the professional way!

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you render the template 'species.html' with an 'animals' variable?

  2. 2. What is Jinja2 in the context of Flask?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    What does the syntax for displaying a species variable look like in Jinja2?

  • Horizontal ordering

    How do you start an if condition in Jinja2?

  • Click in order

    Arrange a for loop iterating over animals in Jinja2:

  • Vertical ordering

    Arrange the structure of a Jinja2 template with inheritance:

  • Code editor

    Write a template with a for loop displaying animal names in <li> elements.

  1. Questionrender_template
  2. QuestionWhat is Jinja2?
  3. Put in orderDisplaying a Jinja2 variable
  4. QuestionDisplaying a variable
  5. QuestionFor loop in Jinja2
  6. Put in orderIf in Jinja2
  7. Click in orderJinja2 for loop
  8. Put in orderTemplate structure
  9. Coding taskCreating a template

Useful articles