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:
Create your project folder:
4. Your First Flask App (app.py)
This code renders an HTML page with dynamic content passed as variables.
5. Create Your First Template (index.html)
Inside the templates/
folder:
When you visit http://127.0.0.1:5000
,
It will show:
Hello, Rasagna!
6. Templating Basics
a. Output with {{ }}
Used to display variables:
b. Control Statements with {% %}
Used for loops and conditions:
7. Using Loops in Templates
users.html:
8. Template Inheritance
DRY (Don't Repeat Yourself) principle in action.
Create a base.html:
Now extend it in index.html:
9. Passing Dictionaries
profile.html:
10. Filters in Jinja2
Jinja2 includes powerful filters to manipulate data.
Examples:
Other useful filters: safe
, capitalize
, title
, default
, join
, replace
, etc.
11. Macros in Templates
Think of macros as reusable mini-templates.
In macros.html:
In form.html:
12. Template Comments
Template comments will not be rendered:
13. Handling Missing Values
Or use the default
filter:
14. Serving Static Files
Place static files like CSS, JS, or images in a static/
folder.
In index.html:
15. Advanced: Nesting Templates
Use {% include %}
for partials:\
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
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. ✨
Learn FullStack Python Course
Comments
Post a Comment