Template Engines (Jinja2 for Flask, Django Templates)

Templates are an essential part of web development, allowing us to separate HTML structure from backend logic. In this tutorial, we will explore template engines used in Flask and Django:

  • Jinja2 (used in Flask)
  • Django Templates (used in Django)

1. Why Use a Template Engine?

A template engine helps in dynamically generating HTML content. Instead of manually inserting values in HTML files, we can use placeholders and control structures like loops and conditions.

Benefits of Template Engines

  • Code Reusability – Create a single template and reuse it for multiple pages.
  • Separation of Logic & Design – Keep HTML files clean while handling data in the backend.
  • Security – Prevents XSS (Cross-Site Scripting) attacks by escaping user input.

2. Django Template Engine

Django comes with a built-in template engine, which automatically loads and renders templates.

2.1 Creating a Template in Django

In a Django project, templates are usually stored in a templates folder inside the app directory.

Example: Create an HTML file home.html in the templates/ folder

<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Hello, {{ user_name }}!</h1>
    <p>Today's date is: {{ current_date }}</p>
</body>
</html>

2.2 Rendering a Template in Django Views

In views.py, use the render() function to send data to the template.

from django.shortcuts import render
from datetime import datetime
def home(request):
    context = {
        'user_name': 'Rahul',
        'current_date': datetime.now()
    }
    return render(request, 'home.html', context)

Now, when you visit http://127.0.0.1:8000/, it will display: 
Hello, Rahul! 
Today's date is: [current date]


2.3 Template Tags in Django

Django templates allow you to use template tags like loops and conditions.

Example: If-Else Condition
{% if user_name %}
    <h2>Welcome, {{ user_name }}!</h2>
{% else %}
    <h2>Welcome, Guest!</h2>
{% endif %}
Example: For Loop
<ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>

3. Jinja2 Template Engine (Used in Flask)

Flask uses Jinja2 as its default template engine, which is similar to Django Templates but more flexible.

3.1 Creating a Jinja2 Template in Flask

Templates in Flask are stored inside a templates/ folder.

Example: Create templates/home.html

<!DOCTYPE html>
<html>
<head>
    <title>Flask Template</title>
</head>
<body>
    <h1>Welcome, {{ user_name }}!</h1>
    <p>Today's date is: {{ current_date }}</p>
</body>
</html>

3.2 Rendering a Template in Flask

In app.py, use render_template() to send data to the template.

from flask import Flask, render_template
from datetime import datetime
app = Flask(__name__)
@app.route("/")
def home():
    return render_template("home.html", user_name="Amit", current_date=datetime.now())
if __name__ == "__main__":
    app.run(debug=True)

Now, visit http://127.0.0.1:5000/, and you’ll see: 
Welcome, Amit! 
Today's date is: [current date]


3.3 Jinja2 Template Tags in Flask

If-Else Condition

{% if user_name %}
    <h2>Welcome, {{ user_name }}!</h2>
{% else %}
    <h2>Welcome, Guest!</h2>
{% endif %}

For Loop

<ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>

Jinja2 syntax is very similar to Django Templates, making it easy to switch between the two.


4. Comparison: Django Templates vs Jinja2

FeatureDjango TemplatesJinja2 (Flask)
Default inDjangoFlask
FlexibilityLimited (Security-focused)More flexible
PerformanceOptimized for DjangoFaster in some cases
Best forFull-stack Django appsMicroservices, APIs

Django Templates are safer but have stricter rules. 
Jinja2 is more flexible and commonly used outside Django.


5. Conclusion

This tutorial covered template engines in Django and Flask. Both use similar syntax with {% %} for logic and {{ }} for variables.

  • Django Templates are secure and built into Django.
  • Jinja2 is powerful and widely used in Flask.