aiohttp-jinja2
aiohttp-jinja2 is a Jinja2 template renderer designed for integration with aiohttp.web, the HTTP server component of the asyncio-based aiohttp library. Currently at version 1.6, it provides a stable and mature solution for serving dynamic HTML content within aiohttp applications, with releases occurring a few times a year to maintain compatibility and introduce new features.
Warnings
- breaking The `static_root_url` key for accessing static file configuration has been deprecated in favor of `aiohttp.web.AppKey`. Update application configuration to use `AppKey` instances.
- breaking Python 3.7 is no longer supported. The library now requires Python 3.8 or newer.
- breaking Jinja2 versions older than 3.0 are no longer supported. This can lead to package conflicts if other dependencies require older Jinja2 versions.
- deprecated Decorating non-async functions with `@aiohttp_jinja2.template` is no longer supported. All web handlers using this decorator must be `async` functions.
- gotcha Asynchronous functions (coroutines) cannot be directly called from within Jinja2 templates. They must be awaited in the handler before passing their results to the template context.
- gotcha When using `aiohttp.web.RouteTableDef` with `@aiohttp_jinja2.template`, the `@template` decorator must be applied *before* the `@routes.get()` (or other HTTP method) decorator.
Install
-
pip install aiohttp-jinja2
Imports
- setup
import aiohttp_jinja2 from aiohttp import web import jinja2 app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates')) - template
from aiohttp import web import aiohttp_jinja2 @routes.get('/hello') @aiohttp_jinja2.template('index.html') async def handler(request: web.Request): return {'name': 'World'} - render_template
from aiohttp import web import aiohttp_jinja2 async def handler(request: web.Request): context = {'data': 'Some info'} response = aiohttp_jinja2.render_template('page.html', request, context) response.headers['Content-Language'] = 'en' return response
Quickstart
import os
from aiohttp import web
import aiohttp_jinja2
import jinja2
async def hello_page(request):
name = request.match_info.get('name', 'Anonymous')
return {'name': name, 'title': 'Hello Page'}
async def welcome_page(request):
return {'title': 'Welcome'}
def setup_routes(app):
aiohttp_jinja2.setup(
app,
loader=jinja2.FileSystemLoader(
os.path.join(os.path.dirname(__file__), 'templates')
)
)
routes = web.RouteTableDef()
@routes.get('/')
@aiohttp_jinja2.template('index.html')
async def index(request: web.Request):
return await welcome_page(request)
@routes.get('/hello/{name}')
@aiohttp_jinja2.template('hello.html')
async def hello(request: web.Request):
return await hello_page(request)
app.add_routes(routes)
if __name__ == '__main__':
app = web.Application()
setup_routes(app)
web.run_app(app, port=8080)