Flask
Jinja2 Templates
Render templates with context and template inheritance.
By EZ4Code Team
templatesjinja2
Code
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/greet/<name>")
def greet(name):
return render_template("greet.html", name=name, items=["a", "b", "c"])
# templates/greet.html
{% extends "base.html" %}
{% block content %}
<h1>Hello {{ name|capitalize }}</h1>
<ul>
{% for item in items %}
<li>{{ loop.index }}: {{ item }}</li>
{% endfor %}
</ul>
{% endblock %}Explanation
render_template() loads a Jinja2 file from the templates/ folder and injects context variables. Templates support inheritance with extends and block, control flow with for and if, and filters like capitalize. Loop variables such as loop.index provide iteration metadata.
More Flask Snippets
Routing
Define routes with methods and dynamic parameters.
Request and Response
Access request data and build custom responses.
Blueprints
Organize an app into modular blueprints.
Session
Store per-user data in signed session cookies.
Error Handling
Register custom error handlers for HTTP exceptions.
Flask-SQLAlchemy
Define models and query them with Flask-SQLAlchemy.