Flask

Flask Templates with Jinja2

2026-04-27

Introduction

Flask uses the Jinja2 templating engine to render dynamic HTML pages. It lets you embed Python-like expressions directly in your HTML.


Setting Up Templates

Create a folder called templates in your project root. Flask looks there automatically.


Your First Template

Create templates/index.html with the following content.


{{ title }}

{{ heading }}


Passing Data from Flask

Use render_template to pass variables to your template.


return render_template("index.html", title="Home", heading="Welcome!")


Control Flow in Templates

Jinja2 supports if statements and for loops.


{% if user %}

Hello, {{ user }}!

{% else %}

Please log in.

{% endif %}


{% for item in items %}

  • {{ item }}
  • {% endfor %}


    Template Inheritance

    Use a base template to avoid repeating HTML across pages.


    In base.html, define a block.


    {% block content %}{% endblock %}


    In child templates, extend and fill the block.


    {% extends "base.html" %}

    {% block content %}

    Page content here

    {% endblock %}


    Filters

    Jinja2 filters transform values inline.


    {{ name | upper }}

    {{ items | length }}

    {{ text | truncate(100) }}