What are Flask Templates?
While APIs return JSON, web applications often need to serve HTML. Flask uses the Jinja2 engine to generate dynamic HTML. This allows you to write standard HTML files with special placeholders and logic that Flask fills in before sending the page to the user's browser.
- Rendering a Template
By default, Flask looks for HTML files in a folder named templates/ at the root of your project. You use the render_template() function to serve these files and pass data to them.
- Jinja2 Syntax Basics
Jinja2 uses specific delimiters to distinguish between plain HTML and Python-like logic.
- {{ variable }}: Expressions used to print output to the page.
- {% statement %}: Control structures like loops or conditionals.
- {# comment #}: Comments that won't appear in the final HTML.
- Template Inheritance
To avoid repeating headers, footers, and navigation bars on every page, Flask uses inheritance. You create a base 'layout' and other pages 'extend' it.
Common Jinja2 Features
| Feature | Syntax | Description |
|---|---|---|
| Filters | {{ name|upper }} | Modifies variables (e.g., uppercase, length) |
| Conditionals | {% if user %}...{% endif %} | Shows content based on logic |
| Includes | {% include 'footer.html' %} | Imports a small snippet of HTML |
| URL Building | {{ url_for('static', filename='style.css') }} | Generates paths to static files |