Skip to content
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