aiohttp-jinja2

1.6 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to set up `aiohttp-jinja2` with an `aiohttp.web` application. It initializes the Jinja2 environment, defines a template directory, and uses the `@aiohttp_jinja2.template` decorator to render HTML responses for different routes. Create a 'templates' directory with `index.html` and `hello.html` files (e.g., `index.html`: `<h1>{{ title }}</h1>`, `hello.html`: `<h1>Hello, {{ name }}!</h1>`).

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)

view raw JSON →