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.
Jinja2 distinguishes templates from standard HTML using three fundamental delimiter pairs:
{{ expression }}: Expressions & Variables (evaluates and prints output to template).{% statement %}: Statements & Control Logic (for loops, conditionals, template inheritance).{# comment #}: Comments (stripped out during rendering; never visible in page source).render_template()Flask automatically looks for templates in a folder named templates/ located in the application's root directory.
app.py):templates/index.html):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.You can register custom Python functions as Jinja2 filters using the @app.template_filter() decorator:
In your HTML template:
|safe filter do?{# comment #} appear in the rendered HTML source code sent to the client browser?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Reverse Routing with url_for, Aborts & Error Handlers | Control Structures, Loops & Conditionals |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.