Control Structures in Jinja: Conditionals and Loops
Learning Objectives: By the end of this lesson, you will be able to:
- Use Jinja’s conditional statements to control template output
- Implement loops to render lists, dictionaries, and more
- Apply the
loopspecial variable for advanced iteration tasks
1. Welcome and Introduction (5 minutes)
Icebreaker Activity
Have you ever seen a website that shows different content depending on whether you’re logged in, or displays a list of products? How do you think this is achieved in templates?
Lesson Overview
- Duration: 60 minutes
- Prerequisites: Day 1 lesson (basic Jinja syntax, variable rendering)
- Materials Needed: Python 3, Jinja2, code editor
2. Learning Objectives and Session Outline (5 minutes)
What We’ll Cover Today:
- Jinja conditionals - if, elif, else
- Jinja loops - for, else, iterating over data
- The
loopspecial variable - Hands-on practice and exercises
- Common pitfalls and troubleshooting
Success Criteria:
By the end of this session, you should be able to use conditionals and loops in Jinja templates to create dynamic, data-driven output.
3. Foundation Knowledge (15-20 minutes)
Core Concepts
Conditionals in Jinja
Conditionals let you show or hide content based on data. They use {% if %}, {% elif %}, {% else %}, and {% endif %}.
Real-World Analogy: Think of a restaurant menu: “If you are vegetarian, show the veggie menu. Else, show the regular menu.”
Why This Matters: Conditionals make templates dynamic, letting you personalize content for users or situations.
Loops in Jinja
Loops let you repeat content for each item in a list, dictionary, or other sequence. Use {% for item in sequence %} and {% endfor %}.
Real-World Analogy: Imagine writing a thank-you card to each guest at a party. You’d repeat the message for each name on your list.
Why This Matters: Loops are essential for displaying lists of products, users, posts, and more.
The loop Special Variable
Jinja provides a special loop variable inside for-loops, giving you useful info like the current index, whether it’s the first or last item, and more.
Key Terminology
- Conditional: A statement that controls whether a block of code runs
- Loop: A statement that repeats a block of code for each item in a sequence
- Truthiness: Whether a value is considered true or false in a condition
loopvariable: Special variable with properties likeindex,first,last, etc.
4. Detailed Explanation and Examples (25-30 minutes)
Understanding Jinja Conditionals
Basic If Statement
{% if user.is_admin %}
<p>Welcome, admin!</p>
{% else %}
<p>Welcome, user!</p>
{% endif %}
Using Elif and Comparisons
{% if age < 13 %}
<p>Child</p>
{% elif age < 20 %}
<p>Teenager</p>
{% else %}
<p>Adult</p>
{% endif %}
Checking for Existence or Truthiness
{% if items %}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% else %}
<p>No items found.</p>
{% endif %}
Understanding Jinja Loops
Looping Over a List
<ul>
{% for product in products %}
<li>{{ product }}</li>
{% endfor %}
</ul>
Looping Over a Dictionary
<ul>
{% for key, value in user.items() %}
<li>{{ key }}: {{ value }}</li>
{% endfor %}
</ul>
Using the loop Variable
<ul>
{% for item in items %}
<li>{{ loop.index }}. {{ item }} {% if loop.first %}(First){% endif %}</li>
{% endfor %}
</ul>
Looping with Conditions
<ul>
{% for product in products %}
{% if product.in_stock %}
<li>{{ product.name }} - In Stock</li>
{% else %}
<li>{{ product.name }} - Out of Stock</li>
{% endif %}
{% endfor %}
</ul>
Practical Applications
- Show different navigation for logged-in vs. guest users
- Display product lists, user tables, or blog posts
- Add row numbers or alternate row colors in tables
Common Misconceptions
- Misconception: You can use Python’s
fororifdirectly in templates. Reality: Jinja uses its own syntax for control structures. - Misconception: The
loopvariable is available everywhere. Reality:looponly exists inside a for-loop.
5. Live Coding Demonstration (20-25 minutes)
Example 1: Conditional Rendering
from jinja2 import Template
template = Template('''
{% if is_logged_in %}
Welcome back!
{% else %}
Please log in.
{% endif %}
''')
print(template.render(is_logged_in=True))
print(template.render(is_logged_in=False))
Explanation:
- Shows how to display different messages based on a variable
Example 2: Looping with the loop Variable
from jinja2 import Template
template = Template('''
<ul>
{% for item in items %}
<li>{{ loop.index }}: {{ item }}</li>
{% endfor %}
</ul>
''')
print(template.render(items=['Apple', 'Banana', 'Cherry']))
Key Points:
- Demonstrates numbering items in a list
- Shows use of
loop.index
Example 3: Looping Over a Dictionary
from jinja2 import Template
template = Template('''
<ul>
{% for key, value in user.items() %}
<li>{{ key }}: {{ value }}</li>
{% endfor %}
</ul>
''')
user = {'name': 'Alice', 'city': 'Wonderland'}
print(template.render(user=user))
Debugging Demonstration
# Common mistake: using Python syntax
# Incorrect:
template = Template('{% if user == "admin" %}Admin{% endif %}')
# Correct:
template = Template('{% if user == "admin" %}Admin{% endif %}')
# Common mistake: using loop variable outside loop
# Incorrect:
template = Template('{{ loop.index }}')
# Output: '' (blank)
6. Hands-On Practice (30-40 minutes)
Exercise 1: Basic Practice (10 minutes)
Objective: Use conditionals to display a message based on user status
Instructions:
- Create a template that shows “Welcome, admin!” if
is_adminis True, else “Welcome, user!” - Render it with both values for
is_admin.
Starter Code:
from jinja2 import Template
template = Template('''
{% if is_admin %}
Welcome, admin!
{% else %}
Welcome, user!
{% endif %}
''')
print(template.render(is_admin=True))
print(template.render(is_admin=False))
Exercise 2: Intermediate Challenge (15 minutes)
Objective: Display a product list with stock status
Requirements:
- Loop over a list of products (each a dict with
nameandin_stock) - Show product name and “In Stock” or “Out of Stock”
- Use the
loopvariable to number the products
Hints:
- Use
{% for ... %}and{% if ... %} - Access product fields with
product['name']orproduct.name
Exercise 3: Creative Application (15 minutes)
Objective: Render a table of users with alternating row colors
Challenge:
- Loop over a list of users (dicts with
nameandrole) - Use
loop.cycle('even', 'odd')to alternate row classes - Add a message if the user list is empty
Extension Ideas:
- Add a column for user status (active/inactive)
- Highlight admins with a special style
7. Common Pitfalls and Troubleshooting (10 minutes)
Frequent Mistakes
-
Problem: Using Python syntax instead of Jinja Cause: Forgetting Jinja’s unique syntax Solution: Review Jinja’s
{% %}and{{ }}usage -
Problem: Accessing
loopoutside a for-loop Cause: Misunderstanding scope Solution: Only useloopinside{% for %}blocks
Debugging Tips
- Print your data before rendering to check structure
- Use
{% else %}in loops to handle empty lists - Add comments with
{# ... #}to clarify logic
8. Best Practices and Professional Tips (5 minutes)
Industry Standards
- Keep logic simple in templates
- Use the
loopvariable for advanced iteration - Prefer
{% else %}in loops for empty data - Test templates with different data sets
Next Steps in Your Learning Journey
- Explore Jinja filters and tests
- Try nesting loops and conditionals
- Read the Jinja documentation on control structures
9. Summary and Review (5 minutes)
Key Takeaways
- Jinja conditionals and loops make templates dynamic
- The
loopvariable provides powerful iteration features - Use Jinja’s syntax, not Python’s, in templates
Quick Review Questions
- How do you write an if-else block in Jinja?
- What does the
loop.indexvariable do? - How can you handle empty lists in a for-loop?
For Instructors
Teaching Tips
- Use real-world data for exercises
- Emphasize the difference between Python and Jinja syntax
- Allow students to experiment with the
loopvariable
Assessment Ideas
- Code review of student templates
- Peer feedback on dynamic output
- Short quiz on control structures
Adaptation Notes
- For beginners: Focus on simple if/else and for-loops
- For advanced: Introduce nested loops and custom conditions
- For online: Use collaborative coding tools for group exercises