CodingNic

Flask Fundamentals

Templates and Jinja

Flask Fundamentals 12 min read

Templates and Jinja

Templates and Jinja

So far, your Flask app returns plain text.

To build real web applications, you need to return HTML pages.

Templates allow you to separate your logic from your presentation.

What are Templates?

Templates are HTML files that define how your application looks.

Instead of returning plain text, Flask can render HTML using templates.

What is Jinja?

Jinja is the template engine used by Flask.

It allows you to:

  • Insert dynamic data into HTML
  • Use logic inside templates
  • Reuse layout components

Creating a Template

Create a templates/ folder and add a file called index.html:

id="html-template"
<!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h1>Hello, {{ name }}</h1> </body> </html>

Rendering a Template

Update your Flask app:

id="render-template"
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): return render_template("index.html", name="Alice")

How It Works

  • Flask receives the request
  • It loads the template
  • Jinja injects data into the template
  • HTML is returned to the browser

Templates Flow Diagram

Jinja Syntax

Jinja uses special syntax:

  • {{ }} → output variables
  • {% %} → logic (loops, conditions)

Example:

id="jinja-loop"
<ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul>

Why Templates Matter

Templates help you:

  • Separate backend logic from frontend
  • Build dynamic pages
  • Reuse layouts across pages

Challenge

Display dynamic data in a template.

What to do

  1. Create a file profile.html inside the templates/ folder

  2. Add HTML with:

    • A heading showing a name
    • A paragraph showing age
  3. Use Jinja syntax {{ }} to display variables

  4. In your Flask route:

    • Use render_template()

    • Pass values like:

      • name = “Alice”
      • age = 25

Bonus

Create a list of hobbies and display them using a loop.

What you should see

  • The page shows dynamic data from Flask

Summary

  • Templates define HTML structure
  • Jinja adds dynamic behavior
  • Flask renders templates into responses

In the next lesson, you’ll learn how to serve static files like CSS and JavaScript.