Learn Flask Β· 3/15

Templates and UI (Jinja2): Bringing Your App to Life

7 min read

Templates and UI (Jinja2): Bringing Your App to Life 🎨

Welcome back! So far, our Flask application can only send back simple text. That's like having a restaurant that only serves plain crackers. πŸ€·β€β™‚οΈ Let's be honest, nobody's going to be raving about that. To build a real web application, we need to serve up some beautifully structured HTML, and that's where Jinja2, the powerful template engine for Flask, comes into play.

Think of it this way: your Python code is the brilliant chef who gathers all the ingredients (data), and Jinja2 is the master food artist who arranges those ingredients on the plate (HTML) to make it look appetizing for your users.

Ready to spice things up? Let's get cooking!


1. Introduction to Jinja2: Rendering HTML Dynamically πŸš€

The Problem:

Imagine you want to display a user's profile page. With plain HTML, you would have to create a separate .html file for every single user. If you have a thousand users, you'd be creating a thousand HTML files. That sounds like a nightmare, right? 😱 This is where static HTML falls short; it can't change based on user data or other conditions.

The Solution: Jinja2 to the Rescue!

Jinja2 is a "template engine." It lets you create a single HTML file (a template) and use special placeholders and logic. Flask then uses Jinja2 to "render" this template, which means it fills in the blanks with actual data and logic before sending it to the user's browser. This way, one profile.html template can serve every user, dynamically showing their specific information.

How does it work under the hood?

When you tell Flask to render a template, it hands over the HTML file and any data you provide to the Jinja2 engine. Jinja2 then scans the file for its special syntax (like {{ ... }} and {% ... %}), executes any logic, and replaces the placeholders with the data you passed in. The result is a standard, complete HTML file that gets sent to the user.

Getting Started:

First, you need a templates folder in the root of your Flask project. Flask will automatically look for your HTML files in this directory.

bash
/your_flask_app
β”œβ”€β”€ app.py
└── /templates
    └── index.html

Now, let's create a simple template in templates/index.html:

html
<!DOCTYPE html>
<html>
<head>
    <title>My First Jinja Template</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

Notice the {{ name }} part? That's a Jinja2 placeholder for a variable.


2. Passing Context: Sending Python Data to Templates πŸ“¦

The Problem:

Our template has a placeholder {{ name }}, but how do we tell it what name is? The template itself has no idea. It's like a fill-in-the-blanks puzzle with no word bank.

The Solution: The render_template Function

Flask's render_template function is the bridge between your Python backend and your Jinja2 frontend. You can pass keyword arguments to this function, and those arguments become the variables available in your template.

Let's update our app.py:

python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    # We are passing the variable 'name' with the value 'Alex' to our template.
    return render_template('index.html', name='Alex')

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

When you run this and go to your browser, you will see "Hello, Alex!". If you change 'Alex' to 'Brenda', the page will say "Hello, Brenda!". We've just made our HTML dynamic! πŸŽ‰

You can pass all sorts of Python data types, like strings, integers, lists, and even dictionaries.

python
@app.route('/user-profile')
def user_profile():
    user_info = {
        "username": "coder_cat",
        "email": "[email protected]",
        "likes": ["Napping", "Treats", "Coding"]
    }
    return render_template('profile.html', user=user_info)

3. Control Structures: If Statements and For Loops in HTML 🧠

Your chef (Python) can now send ingredients (data) to the food artist (Jinja2). But what if the artist needs to make decisions? "If the customer wants extra cheese, add it. For every topping they ordered, place it on the pizza." This is where control structures come in.

The Problem:

How do you show a "Login" button to guests but a "Logout" button to logged-in users on the same page? Or how do you display a list of items from your database without hardcoding each one in HTML?

The Solution: Jinja2's {% ... %} Blocks

Jinja2 provides if statements and for loops right inside your HTML, enclosed in {% ... %}.

If Statements:

Let's show a different message based on whether a user is logged in.

app.py:

python
@app.route('/dashboard')
def dashboard():
    is_logged_in = True  # In a real app, this would be based on session data
    return render_template('dashboard.html', user_logged_in=is_logged_in)

templates/dashboard.html:

html
<!DOCTYPE html>
<html>
<body>
    {% if user_logged_in %}
        <h1>Welcome back, valued user!</h1>
        <button>Logout</button>
    {% else %}
        <h1>Please log in to continue.</h1>
        <a href="/login">Login</a>
    {% endif %}
</body>
</html>

Here, Jinja2 checks the value of user_logged_in. If it's True, it renders the first block; otherwise, it renders the else block. Notice the {% endif %}β€”it's required to close the if block.

For Loops:

Now, let's display that list of a user's likes we created earlier.

app.py:

python
@app.route('/user-profile')
def user_profile():
    user_info = {
        "username": "coder_cat",
        "email": "[email protected]",
        "likes": ["Napping", "Treats", "Coding"]
    }
    return render_template('profile.html', user=user_info)

templates/profile.html:

html
<!DOCTYPE html>
<html>
<body>
    <h1>{{ user.username }}'s Profile</h1>
    <p>Email: {{ user.email }}</p>
    <h3>Likes:</h3>
    <ul>
        {% for item in user.likes %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>

The for loop iterates through the user.likes list, and for each item, it creates a new <li> element. This is incredibly powerful because you don't need to know how many items are in the list beforehand. Just like with if, you must close the loop with {% endfor %}.

A funny thought: Imagine if you had to manually write an <li> for every user on a social media site. You'd still be writing them from the days of MySpace. πŸ˜‚


4. Template Inheritance: Keeping Your Code DRY with Base Layouts πŸ›οΈ

The Problem:

As your website grows, you'll notice that many pages share the same structure: the same header, navigation bar, and footer. Are you going to copy and paste that same block of HTML into every single template file? Please don't. That's a violation of the "Don't Repeat Yourself" (DRY) principle. If you need to change one link in your navigation bar, you'd have to do it in every file. What a pain!

The Solution: {% extends %} and {% block %}

Jinja2 allows you to create a base "skeleton" template and then have other templates "inherit" from it. The child templates can then fill in or override specific sections.

Let's create a base.html:

templates/base.html:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}My Awesome Site{% endblock %}</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <nav>
        <a href="/">Home</a>
        <a href="/about">About</a>
    </nav>
    <main>
        {% block content %}{% endblock %}
    </main>
    <footer>
        <p>&copy; 2026 My Awesome Site, Inc.</p>
    </footer>
</body>
</html>

The {% block ... %} sections are like empty spaces that child templates can fill.

Now, let's create a home.html that inherits from our base.

templates/home.html:

html
{% extends "base.html" %}

{% block title %}
    Home Page - My Awesome Site
{% endblock %}

{% block content %}
    <h1>Welcome to the Home Page!</h1>
    <p>This is where the main content for the home page goes.</p>
{% endblock %}

What's happening here?

  1. {% extends "base.html" %} tells Jinja2 to use base.html as the foundation. This line must be the very first thing in the template.
  2. We then define the blocks that we want to fill in. Here, we're providing content for the title and content blocks.
  3. When Flask renders home.html, Jinja2 will first load base.html and then inject the blocks from home.html into the corresponding empty blocks in the base template.

Now you can have dozens of pages all extending the same base.html. Need to add a "Contact" link to your navigation? You only have to change it in one place: base.html. So much cleaner and less error-prone! ✨


Further Reading and References:

Challenge

You are tasked with building a dynamic user profile page using Flask and Jinja2. This will require you to create a Python Flask application, a base HTML template, and a profile-specific template that inherits from the base.

You will write the code for three separate conceptual "files" in the editor below: app.py, templates/base.html, and templates/profile.html.

app.py Requirements:

  1. Create a Flask application.
  2. Define a single route at /profile.
  3. In the route's function, create a Python dictionary containing user data with the following structure:
    • username: A string (e.g., 'casey')
    • is_active: A boolean (e.g., True)
    • likes: A list of strings (e.g., ['Python', 'Flask', 'Jinja2'])
  4. Use the render_template function to render profile.html and pass the entire user data dictionary to it.

templates/base.html Requirements:

  1. Create a basic HTML5 structure.
  2. The <body> should contain a <header> with an <h1> element containing any title you want.
  3. Define a Jinja2 block named content where the main page content will go.
  4. Include a <footer> with some placeholder text.

templates/profile.html Requirements:

  1. This template must inherit from base.html.
  2. Override the content block from the parent template.
  3. Inside the content block, you must:
    • Display the username from the context data in an <h2> tag.
    • Use a Jinja2 if statement to display the user's status. If is_active is True, show "<p>Status: Online</p>"; otherwise, show "<p>Status: Offline</p>".
    • Display the user's likes in an unordered list (<ul>). Use a Jinja2 for loop to iterate through the list. If the likes list is empty, the for loop must use an {% else %} clause to display a single list item: <li>No likes to show.</li>.

Expected result

Your solution should contain three distinct code blocks, correctly implementing the logic for app.py, templates/base.html, and templates/profile.html.

app.py:
A complete Flask application that defines a /profile route. This route must create a dictionary with username, is_active, and likes keys and pass it to render_template('profile.html', ...). The dictionary itself must be passed as a keyword argument to the template.

templates/base.html:
A valid HTML5 document containing header, footer, and a {% block content %}{% endblock %} section within the <body>.

templates/profile.html:
A template that starts with {% extends "base.html" %}. It must contain a {% block content %} which correctly uses {{ ... }} to display the username, a {% if ... %} block for the status, and a {% for ... %}{% else %}{% endfor %} block to display the list of likes or a fallback message.

python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.