Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

Chapter 17: Rendering HTML with Jinja2

Razor views and Jinja2 templates solve the same broad problem: mix static markup with server-provided data.

Jinja2 layout:

<!-- templates/layout.html -->
<!doctype html>
<html lang="en">
  <head>
    <title>{% block title %}RecipeVault{% endblock %}</title>
  </head>
  <body>
    <main>{% block content %}{% endblock %}</main>
  </body>
</html>

Page:

{% extends "layout.html" %}

{% block title %}Recipes{% endblock %}

{% block content %}
  <h1>Recipes</h1>
  <ul>
    {% for recipe in recipes %}
      <li><a href="/recipes/{{ recipe.id }}">{{ recipe.title }}</a></li>
    {% endfor %}
  </ul>
{% endblock %}

Template practices: