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
Control Structures, Loops & Conditionals0%
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
HomeTutorialsFlaskControl Structures, Loops & Conditionals
Template Inheritance & Layout Composition

Control Structures, Loops & Conditionals

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

Dynamic web pages require conditional branching and iterative rendering. Jinja2 provides robust control structures enclosed within {% ... %} blocks, including if/elif/else conditions and feature-rich for loops.


1. Conditionals (if, elif, else)

Jinja2 conditionals mirror Python's logical evaluation rules, checking for truthy and falsy values:

1{% if user.is_authenticated %}
2 <div class="user-menu">
3 <span>Signed in as <strong>{{ user.username }}</strong></span>
4 {% if user.role == 'admin' %}
5 <a href="/admin" class="btn btn-warning">Admin Panel</a>
6 {% elif user.role == 'instructor' %}
7 <a href="/portal" class="btn btn-info">Teacher Portal</a>
8 {% else %}
9 <a href="/student" class="btn btn-primary">My Courses</a>
10 {% endif %}
11 <a href="/logout">Logout</a>
12 </div>
13{% else %}
14 <div class="auth-buttons">
15 <a href="/login">Log In</a>
16 <a href="/register">Create Account</a>
17 </div>
18{% endif %}

You can combine conditions with boolean operators and, or, not, and identity checks is defined, is none:

1{% if discount > 0 and not is_expired %}
2 <span class="badge">Special Offer Active!</span>
3{% endif %}

2. Iteration with for Loops

Iterate over lists, tuples, dictionaries, and database querysets:

1<ul class="courses-list">
2{% for course in courses %}
3 <li class="course-card">
4 <h3>{{ course.title }}</h3>
5 <p>Instructor: {{ course.instructor }}</p>
6 <span class="price">₹{{ course.price }}</span>
7 </li>
8{% endfor %}
9</ul>

Empty List Handling with {% else %}

Jinja2 provides a built-in else block inside for loops that renders when the collection is empty:

1<ul class="notifications">
2{% for alert in user.notifications %}
3 <li>{{ alert.message }} ({{ alert.date }})</li>
4{% else %}
5 <li class="empty-state">No new notifications. You are all caught up!</li>
6{% endfor %}
7</ul>

3. The Special loop Variable

Inside every {% for %} loop, Jinja2 provides an automatic loop context variable containing execution metadata:

VariableTypeDescription
loop.indexint1-based iteration counter (1, 2, 3...)
loop.index0int0-based iteration counter (0, 1, 2...)
loop.revindexintIterations remaining until the end (1-based)
loop.firstboolTrue during the first iteration
loop.lastboolTrue during the final iteration
loop.lengthintTotal number of items in the iterable sequence
loop.cyclemethodAlternate between arguments: loop.cycle('odd', 'even')

Practical Example: Zebra-Striped Tables & Badges

1<table class="table">
2 <thead>
3 <tr>
4 <th>#</th>
5 <th>Student Name</th>
6 <th>Enrolled Date</th>
7 <th>Action</th>
8 </tr>
9 </thead>
10 <tbody>
11 {% for student in students %}
12 <tr class="{{ loop.cycle('bg-white', 'bg-slate-50') }}">
13 <td>{{ loop.index }}</td>
14 <td>
15 {{ student.name }}
16 {% if loop.first %}
17 <span class="badge bg-gold">Top Student</span>
18 {% endif %}
19 </td>
20 <td>{{ student.enrolled_at }}</td>
21 <td><a href="/students/{{ student.id }}">View</a></td>
22 </tr>
23 {% endfor %}
24 </tbody>
25</table>

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What statement handles an empty list inside a Jinja2 {% for %} loop without requiring a separate if check?
Question 2
What is the value of loop.index during the very first iteration of a Jinja2 loop?
Question 3
How do you alternate row CSS classes between 'odd' and 'even' in a Jinja2 loop?
Question 4
Which boolean expression checks if a variable user_bio is explicitly defined in the template context?
Question 5
How must an {% if %} conditional block be terminated in Jinja2?
Next Lesson

Template Inheritance & Layout Composition

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

Related Lessons

Previous LessonNext Lesson
Jinja2 Syntax, Variables & Custom FiltersTemplate Inheritance & Layout Composition

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