Menu

Django & Flask Topic

Flask Jinja2 Templating Basics

What is Jinja2?

Jinja2 is a modern and designer-friendly templating language for Python. It allows you to embed Python-like expressions in HTML, making your web pages dynamic.

1. Basic Variable Output

The most fundamental concept: displaying data from your Python code in HTML.

Flask View:

python

@app.route('/user')
def user_profile():
    user_data = {
        'name': 'John Doe',
        'age': 25,
        'email': 'john@example.com'
    }
    return render_template('profile.html', user=user_data)

Template (profile.html):

html

<!DOCTYPE html>
<html>
<head>
    <title>User Profile</title>
</head>
<body>
    <h1>Welcome, {{ user.name }}!</h1>
    <p>Age: {{ user.age }}</p>
    <p>Email: {{ user.email }}</p>
</body>
</html>

2. Control Structures

If Statements

html

<div class="user-status">
    {% if user.age >= 18 %}
        <p class="adult">This user is an adult</p>
    {% else %}
        <p class="minor">This user is a minor</p>
    {% endif %}
</div>

For Loops

html

x
<div class="user-status">
    {% if user.age >= 18 %}
        <p class="adult">This user is an adult</p>
    {% else %}
        <p class="minor">This user is a minor</p>
    {% endif %}
</div>

3. Template Inheritance (The Most Powerful Feature)

This allows you to create a base template with common structure and override specific parts in child templates.

Base Template (base.html)

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}My Website{% endblock %}</title>
    <link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
    <header>
        <nav>
            <a href="/">Home</a>
            <a href="/about">About</a>
            <a href="/contact">Contact</a>
        </nav>
    </header>
    
    <main>
        {% block content %}
        <!-- Default content can go here -->
        {% endblock %}
    </main>
    
    <footer>
        {% block footer %}
        <p>&copy; 2024 My Website. All rights reserved.</p>
        {% endblock %}
    </footer>
</body>
</html>

Child Template (home.html)

html

{% extends "base.html" %}

{% block title %}Home Page - My Website{% endblock %}

{% block content %}
    <h1>Welcome to our Home Page!</h1>
    <p>This content replaces the block in base.html</p>
    
    <div class="featured-products">
        <h2>Featured Products</h2>
        {% for product in products %}
            <div class="product">
                <h3>{{ product.name }}</h3>
                <p>Price: ${{ product.price }}</p>
            </div>
        {% endfor %}
    </div>
{% endblock %}

{% block footer %}
    <p>&copy; 2024 My Website. Special home page footer.</p>
{% endblock %}

4. Filters

Filters transform variable output. They're applied using the pipe symbol (|).

html

<!-- String filters -->
<p>{{ title|upper }}</p>
<p>{{ description|truncate(50) }}</p>
<p>{{ name|default("Anonymous") }}</p>

<!-- Number filters -->
<p>Price: {{ price|round(2) }}</p>
<p>Items: {{ items|length }}</p>

<!-- Date filters -->
<p>Joined: {{ join_date|datetime }}</p>

5. Includes

Break your templates into reusable components:

header.html:

html

<header class="site-header">
    <h1>My Awesome Site</h1>
    <nav>...</nav>
</header>

footer.html:

html

<footer class="site-footer">
    <p>Contact us at: info@example.com</p>
</footer>

Main template:

html

<!DOCTYPE html>
<html>
<head>...</head>
<body>
    {% include 'header.html' %}
    
    <main>
        {% block content %}{% endblock %}
    </main>
    
    {% include 'footer.html' %}
</body>
</html>

6. Macros (Like Functions for Templates)

Create reusable template components:

macros.html:

html

{% macro render_product(product) %}
    <div class="product-card">
        <h3>{{ product.name }}</h3>
        <p class="price">${{ product.price }}</p>
        {% if product.on_sale %}
            <span class="sale-badge">On Sale!</span>
        {% endif %}
    </div>
{% endmacro %}

Using the macro:

html

{% import "macros.html" as macros %}

<div class="product-grid">
    {% for product in products %}
        {{ macros.render_product(product) }}
    {% endfor %}
</div>

7. Complete Practical Example

Let's see all these concepts working together:

Flask App:

python

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    products = [
        {'name': 'Laptop', 'price': 999.99, 'on_sale': True},
        {'name': 'Mouse', 'price': 25.50, 'on_sale': False},
        {'name': 'Keyboard', 'price': 75.00, 'on_sale': True}
    ]
    
    user = {'name': 'Alice', 'is_premium': True}
    
    return render_template('store.html', 
                         products=products, 
                         user=user, 
                         title="Our Store")

Templates structure:

text

templates/
    base.html
    store.html
    macros/
        product.html

base.html:

html

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Store{% endblock %}</title>
    <style>
        .sale-badge { color: red; font-weight: bold; }
        .premium-user { background-color: gold; }
    </style>
</head>
<body>
    {% include 'partials/header.html' %}
    <main>{% block content %}{% endblock %}</main>
    {% include 'partials/footer.html' %}
</body>
</html>

store.html:

html

{% extends "base.html" %}
{% import "macros/product.html" as product_macros %}

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

{% block content %}
<div class="store-container {% if user.is_premium %}premium-user{% endif %}">
    <h1>Welcome, {{ user.name }}!</h1>
    
    {% if user.is_premium %}
        <p class="premium-message">🎉 Enjoy your premium benefits!</p>
    {% endif %}
    
    <div class="products">
        <h2>Our Products ({{ products|length }} items)</h2>
        
        {% for product in products %}
            {{ product_macros.render_product(product) }}
        {% else %}
            <p>No products available at the moment.</p>
        {% endfor %}
    </div>
</div>
{% endblock %}

Django Connection

When you move to Django, you'll find the template concepts are nearly identical:

  • Variables: {{ variable }} (same)

  • Tags: {% tag %} (same)

  • Inheritance: {% extends %} and {% block %} (same)

  • Includes: {% include %} (same)

The main differences are in the specific filters and tags available, but the mental model is exactly the same.

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?