Using Jinja2 Templates in Flask

Using Jinja2 Templates in Flask

1. Introduction

Flask is a popular micro web framework in Python.
One of its biggest strengths is how smoothly it integrates with Jinja2, a powerful templating engine.
This allows developers to build dynamic, clean, and maintainable web pages.

Let’s explore how to use Jinja2 with Flask — step by step, in simple terms.


2. What is Jinja2?

Jinja2 is a templating engine for Python, inspired by Django templates.
It allows you to embed Python-like expressions inside HTML using {{ }} and {% %}.

This is what makes Flask powerful for web development — logic stays in Python, UI in HTML.


3. Setting Up Your Flask Project

Let’s get started:

pip install Flask

Create your project folder:

flask_jinja_demo/ │ ├── app.py ├── templates/ │ └── index.html

4. Your First Flask App (app.py)

from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template("index.html", name="Rasagna", title="Home Page") if __name__ == '__main__': app.run(debug=True)

This code renders an HTML page with dynamic content passed as variables.


5. Create Your First Template (index.html)

Inside the templates/ folder:

<!DOCTYPE html> <html> <head> <title>{{ title }}</title> </head> <body> <h1>Hello, {{ name }}!</h1> <p>Welcome to your first Jinja2-powered Flask app.</p> </body> </html>

When you visit http://127.0.0.1:5000,
It will show:
Hello, Rasagna!


6. Templating Basics

a. Output with {{ }}

Used to display variables:

<p>{{ user }}</p>

b. Control Statements with {% %}

Used for loops and conditions:

{% if user %} <p>Hello, {{ user }}!</p> {% else %} <p>Hello, Guest!</p> {% endif %}

7. Using Loops in Templates

@app.route('/users') def users(): user_list = ["Alice", "Bob", "Charlie"] return render_template("users.html", users=user_list)

users.html:

<h2>User List:</h2> <ul> {% for user in users %} <li>{{ user }}</li> {% endfor %} </ul>

8. Template Inheritance

DRY (Don't Repeat Yourself) principle in action.
Create a base.html:

<!DOCTYPE html> <html> <head> <title>{% block title %}My Site{% endblock %}</title> </head> <body> <header><h1>Flask Demo</h1></header> <main> {% block content %}{% endblock %} </main> </body> </html>

Now extend it in index.html:

{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %} <h2>Hello, {{ name }}</h2> <p>This is the homepage.</p> {% endblock %}

9. Passing Dictionaries

@app.route('/profile') def profile(): user = {'name': 'Rasagna', 'age': 23, 'city': 'Hyderabad'} return render_template("profile.html", user=user)

profile.html:

<h2>Profile</h2> <p>Name: {{ user.name }}</p> <p>Age: {{ user.age }}</p> <p>City: {{ user.city }}</p>

10. Filters in Jinja2

Jinja2 includes powerful filters to manipulate data.

Examples:

<p>{{ name|upper }}</p> → RASAGNA <p>{{ name|lower }}</p> → rasagna <p>{{ items|length }}</p> → number of items

Other useful filters: safecapitalizetitledefaultjoinreplace, etc.


11. Macros in Templates

Think of macros as reusable mini-templates.

In macros.html:

{% macro input_field(name, type="text") %} <label>{{ name.capitalize() }}:</label> <input type="{{ type }}" name="{{ name }}"><br> {% endmacro %}

In form.html:

{% import 'macros.html' as forms %} <form> {{ forms.input_field('username') }} {{ forms.input_field('password', 'password') }} </form>

12. Template Comments

Template comments will not be rendered:

{# This is a comment #}

13. Handling Missing Values

<p>{{ user.email or "No email available" }}</p>

Or use the default filter:

<p>{{ user.email|default("No email provided") }}</p>

14. Serving Static Files

Place static files like CSS, JS, or images in a static/ folder.

flask_jinja_demo/ │ ├── static/ │ └── style.css ├── templates/ │ └── index.html ├── app.py

In index.html:

<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

15. Advanced: Nesting Templates

Use {% include %} for partials:\

{% include 'header.html' %}

Good for reusable sections like navbars or footers.


16. Debugging Templates

If something doesn’t render:

  • Check spelling of variables.

  • Print debug info using {{ variable }}.

  • Use Flask’s debug mode: app.run(debug=True)


17. Final Project Structure Recap

flask_jinja_demo/ │ ├── static/ │ └── style.css ├── templates/ │ ├── base.html │ ├── index.html │ ├── profile.html │ ├── users.html │ └── macros.html ├── app.py

18. Conclusion

Jinja2 empowers Flask developers to separate logic from presentation.
It makes web development cleaner, modular, and efficient.

By understanding template inheritance, filters, loops, and conditionals —
You can build dynamic, interactive sites with ease.

So next time you write HTML in Flask —

Let Jinja2 do the heavy lifting. ✨


Read More




Using Tailind CSS in a Python Web App 

Comments

Popular posts from this blog

What is WebDriver in Selenium? Explained with Java

Tosca System Requirements and Installation Guide (Step-by-Step)

Why Choose Python for Full-Stack Web Development