Jinja Partials
Jinja Partials is a Python library designed for the simple reuse of partial HTML page templates within the Jinja template language, particularly for Python web frameworks. It addresses the 'long template problem' by enabling function-like reusability for HTML fragments. The library is currently active, with its latest version being 0.3.1, and shows a consistent release cadence.
Warnings
- breaking The minimum required Python version for `jinja-partials` is now 3.10.
- gotcha Async rendering issues, specifically `asyncio.run() cannot be called from a running event loop`, were fixed in v0.3.1 for async frameworks (Quart, FastAPI, Starlette).
- gotcha The `app` parameter for `register_starlette_extensions` became optional in v0.3.1. While often passed, its previous mandatory status might cause minor type-checking or linting issues if not updated.
- gotcha Jinja's native `include` directive differs fundamentally from `jinja-partials`. `include` acts like a C++ preprocessor macro without parameters, merely inserting template content. `jinja-partials` provides function-like reusability with explicit parameters and local variable scope, offering a more robust way to manage reusable HTML fragments.
- gotcha A new declarative approach using `PartialsJinjaExtension` was introduced in v0.3.0. This offers an alternative to the `register_..._extensions` functions, particularly useful for declarative Jinja2 environment configurations.
Install
-
pip install jinja-partials
Imports
- register_extensions
from jinja_partials import register_extensions
- register_fastapi_extensions
from jinja_partials import register_fastapi_extensions
- register_starlette_extensions
from jinja_partials import register_starlette_extensions
- register_quart_extensions
from jinja_partials import register_quart_extensions
- register_environment
from jinja_partials import register_environment
- PartialsJinjaExtension
from jinja_partials import PartialsJinjaExtension
Quickstart
import flask
from jinja_partials import register_extensions
import os
app = flask.Flask(__name__)
# Assuming templates are in a 'templates' directory and partials in 'templates/partials'
register_extensions(app)
@app.route('/')
def index():
return flask.render_template('index.html', title='Home Page', user={'name': 'Alice'})
# Example template structure:
# templates/
# index.html
# partials/
# greeting.html
# index.html content:
# <!DOCTYPE html>
# <html>
# <head><title>{{ title }}</title></head>
# <body>
# <h1>Welcome!</h1>
# {{ render_partial('greeting.html', name=user.name) }}
# </body>
# </html>
# partials/greeting.html content:
# <p>Hello, {{ name }} from a partial!</p>
if __name__ == '__main__':
# In a real app, you'd run with `flask run` or a WSGI server.
# For this quickstart, we'll simulate rendering directly.
# You would typically run `app.run(debug=True)`
print("Quickstart setup complete. Run this with a Flask development server.")