Jinja2 Fragments Documentation

PyPI - Version PyPI - Downloads License

Overview

jinja2-fragments is a Python library that enhances Jinja2 templates by allowing you to render individual blocks from templates. This is particularly useful for modern web applications using htmx or other JavaScript-based partial page update techniques, where you often need to render just a section of a page rather than the entire page.

This library was created to enable the pattern of Template Fragments with Jinja2, making it easier to maintain a single source template file for both full page and partial rendering.

Key Features

  • Render specific blocks from Jinja2 templates

  • Support for rendering multiple blocks at once

  • Support for both synchronous and asynchronous rendering

  • Integrations with popular Python web frameworks:

    • Flask

    • Starlette

    • FastAPI (built on Starlette)

    • Quart (async Flask)

    • Sanic

    • Litestar

  • Natural syntax that follows each framework’s conventions

  • Perfect for use with htmx for dynamic UI updates

Quick Start

Installation

Install jinja2-fragments with pip:

pip install jinja2-fragments

The above also works for framework-specific installations.

Basic Usage

Here’s a simple example with vanilla Jinja2. Given the following template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>This is the title</title>
</head>
<body>
    <h1>This is a header</h1>
    {% block content %}
    <p>This is the magic number: {{ magic_number }}.</p>
    {% endblock %}
</body>
</html>

You can render only the content block with:

from jinja2 import Environment, FileSystemLoader, select_autoescape
from jinja2_fragments import render_block

environment = Environment(
    loader=FileSystemLoader("my_templates"),
    autoescape=select_autoescape(("html", "jinja2")),
)
rendered_html = render_block(
    environment, "page.html.jinja2", "content", magic_number=42
)

Which will render:

<p>This is the magic number: 42.</p>

Framework Examples

Each framework has its own integration patterns:

from flask import Flask, render_template
from jinja2_fragments.flask import render_block

app = Flask(__name__)


@app.route("/profile/<username>")
def profile(username):
    return render_template("profile.html.jinja2", username=username)


@app.route("/profile/<username>/details")
def profile_details(username):
    return render_block("profile.html.jinja2", "details", username=username)

Indices and Tables