0

In creating a site with AIOHTTP Web, I might define a route and raise an error like:

async def index(request):
    if some_error_happened:
        raise web.HTTPException(body=b'Some error happened.')
    context = {'page_title': "My Site"}
    response = aiohttp_jinja2.render_template('index.html', request, context)
    return response

This will show the text I specified for body but how can I use Jinja2 with it like normal routes?

I found the module jinja2_error but I don't see how to use it in the context of an aiohttp route.

Paragon512
  • 143
  • 8

1 Answers1

0

Use aiohttp_jinja2.render_string:

async def index(request):
    if some_error_happened:
        raise web.HTTPBadRequest(
            text=aiohttp_jinja2.render_template(
                'index.html', 
                request, 
                {"error": "Some error happened"},
            )
        )
    context = {'page_title': "My Site"}
    response = aiohttp_jinja2.render_template('index.html', request, context)
    return response
Andrew Svetlov
  • 16,730
  • 8
  • 66
  • 69