MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Jinja2 Syntax, Variables & Custom Filters0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
3.1Jinja2 Syntax, Variables & Custom Filters3.2Control Structures, Loops & Conditionals3.3Template Inheritance & Layout Composition3.4Jinja2 Macros & Reusable UI Components
HomeTutorialsFlaskJinja2 Syntax, Variables & Custom Filters
Control Structures, Loops & Conditionals

Jinja2 Syntax, Variables & Custom Filters

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Flask uses Jinja2, a fast, expressive, and extensible templating engine for Python. Jinja2 decouples application business logic from HTML presentation, preventing XSS vulnerabilities through automatic contextual HTML escaping.


1. The Three Primary Jinja2 Delimiters

Jinja2 distinguishes templates from standard HTML using three fundamental delimiter pairs:

  1. 1
    {{ expression }}: Expressions & Variables (evaluates and prints output to template).
  2. 2
    {% statement %}: Statements & Control Logic (for loops, conditionals, template inheritance).
  3. 3
    {# comment #}: Comments (stripped out during rendering; never visible in page source).

2. Rendering Templates with render_template()

Flask automatically looks for templates in a folder named templates/ located in the application's root directory.

Project Layout:

1my_flask_app/
2├── app.py
3└── templates/
4 └── index.html

Python View Code (app.py):

1from flask import Flask, render_template
2 
3app = Flask(__name__)
4 
5@app.route("/")
6def home():
7 user_data = {
8 "username": "Priya Sharma",
9 "role": "Lead Data Scientist",
10 "is_authenticated": True,
11 "skills": ["Python", "Flask", "SQLAlchemy", "PyTorch"]
12 }
13 # Pass variables into template context as keyword arguments
14 return render_template("index.html", user=user_data, page_title="Dashboard")

Template Code (templates/index.html):

1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>{{ page_title }} - MSK Institute</title>
6</head>
7<body>
8 <h1>Welcome, {{ user.username }}!</h1>
9 <p>Role: {{ user['role'] }}</p>
10
11 {# Calculate mathematical expressions directly in Jinja2 #}
12 <p>Total skills: {{ user.skills|length }}</p>
13</body>
14</html>

3. Working with Jinja2 Filters

Filters modify or transform variables before they are rendered on the page. Apply filters using the pipe operator |:

1<!-- Text transformations -->
2<p>{{ user.username|upper }}</p> <!-- PRIYA SHARMA -->
3<p>{{ user.username|lower }}</p> <!-- priya sharma -->
4<p>{{ user.username|title }}</p> <!-- Priya Sharma -->
5 
6<!-- Safe Defaults -->
7<p>{{ bio|default("No bio provided.", true) }}</p>
8 
9<!-- Numeric & List operations -->
10<p>{{ scores|sum }}</p>
11<p>{{ scores|sort }}</p>
12<p>{{ "2026-09-16"|truncate(7) }}</p>
13 
14<!-- Escaping & HTML Raw Injection -->
15<p>{{ raw_html_content|striptags }}</p>
16<p>{{ trusted_html_snippet|safe }}</p>
Important Warning
[!WARNING] Only use the |safe filter on trusted content you authored or sanitized with bleach. Never apply |safe directly to unsanitized user submissions, as this introduces severe Stored Cross-Site Scripting (XSS) vulnerabilities.

4. Creating Custom Template Filters

You can register custom Python functions as Jinja2 filters using the @app.template_filter() decorator:

1from datetime import datetime
2 
3@app.template_filter("currency_inr")
4def format_inr(value):
5 # Formats number into Indian Rupee format
6 try:
7 return f"₹{float(value):,.2f}"
8 except (ValueError, TypeError):
9 return value
10 
11@app.template_filter("time_ago")
12def time_ago(dt):
13 if not isinstance(dt, datetime):
14 return dt
15 now = datetime.now()
16 diff = now - dt
17 if diff.days > 0:
18 return f"{diff.days} days ago"
19 seconds = diff.seconds
20 if seconds >= 3600:
21 return f"{seconds // 3600} hours ago"
22 return f"{seconds // 60} mins ago"

In your HTML template:

1<span class="price">{{ course.price|currency_inr }}</span>
2<span class="date">Posted: {{ article.created_at|time_ago }}</span>

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Which Jinja2 delimiter is used to evaluate expressions and print variables into the rendered HTML?
Question 2
In which directory does Flask search for template files by default?
Question 3
What does the Jinja2 |safe filter do?
Question 4
Which decorator registers a custom Python function as a Jinja2 filter in a Flask application?
Question 5
How do comments written in {# comment #} appear in the rendered HTML source code sent to the client browser?
Next Lesson

Control Structures, Loops & Conditionals

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Reverse Routing with url_for, Aborts & Error HandlersControl Structures, Loops & Conditionals

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext