Skip to content

Templates

Flask uses Jinja2 as its template engine for generating HTML.

Basic Usage:

python
from flask import render_template

@app.get("/")
def index():
    return render_template("index.html", name="Alice")

Template Syntax:

  • Variables:
  • Control: {% if %} ... {% endif %}, {% for x in xs %} ... {% endfor %}
  • Filters: 0, can define custom filters
  • Inheritance: {% extends 'base.html' %} + {% block content %}{% endblock %}

Template Directory Structure:

app/
  templates/
    base.html
    index.html

Examples:

html
<!-- templates/base.html -->
<!doctype html>
<title>{% block title %}Site{% endblock %}</title>
<body>
  <header>Header</header>
  <main>
    {% block content %}{% endblock %}
  </main>
</body>
html
<!-- templates/index.html -->
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
  <h1>Hello, {{ name }}!</h1>
{% endblock %}

Static files are introduced in the next chapter (CSS/JS/images, etc.).

Content is for learning and research only.