Jinja2 Syntax, Variables & Custom Filters
Jinja2 Syntax, Variables & Custom Filters
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
{{ expression }}: Expressions & Variables (evaluates and prints output to template). - 2
{% statement %}: Statements & Control Logic (for loops, conditionals, template inheritance). - 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:
Python View Code (app.py):
Template Code (templates/index.html):
3. Working with Jinja2 Filters
Filters modify or transform variables before they are rendered on the page. Apply filters using the pipe operator |:
|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:
In your HTML template:
Practice Quiz
|safe filter do?{# comment #} appear in the rendered HTML source code sent to the client browser?Control Structures, Loops & Conditionals
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Reverse Routing with url_for, Aborts & Error Handlers | Control Structures, Loops & Conditionals |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.