Jinja2 Templates
Returning plain strings from Flask functions is fine for simple responses, but for real web pages you need HTML. Flask uses Jinja2 as its templating engine. Templates allow you to write HTML with placeholders that get replaced by dynamic data.
Jinja2 templates let you embed Python-like expressions in HTML using `{{ }}` and `{% %}`.
Setting Up Templates
Create a folder called `templates` in your project directory. Flask automatically looks for templates there.
Example Template (`templates/index.html`)
<html>
<head><title>Flask App</title></head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>Rendering a Template in Flask
from flask import render_template
@app.route('/')ndef home():
return render_template('index.html', name='Alice')Jinja2 Syntax Basics
- Variable output: `{{ variable }}` – prints the value.
- Statements (if, for): `{% if condition %} ... {% endif %}`
- Comments: `{# This is a comment #}`
- Filters: `{{ name|upper }}` – applies `upper` filter.
Example with Condition and Loop
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% if user %}
<p>Welcome, {{ user }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}Two Minute Drill
- Templates go in a `templates/` folder.
- Use `render_template('file.html', data=value)` to render.
- `{{ var }}` displays a variable; `{% ... %}` for logic.
- Filters like `|upper`, `|lower`, `|default` modify output.
Need more clarification?
Drop us an email at career@quipoinfotech.com
