jinja2 template renderer for aiohttp.web.


Before template rendering you have to setup jinja2 environment (jinja2.Environment) first:

app = web.Application()

After that you may use template engine in your web-handlers. The most convenient way is to decorate a web-handler.

Using the function based web handlers:

def handler(request):
    return {'name': 'Andrew', 'surname': 'Svetlov'}

Or the class-based views (aiohttp.web.View):

class Handler(web.View):
    async def get(self):
        return {'name': 'Andrew', 'surname': 'Svetlov'}

On handler call the template() decorator will pass returned dictionary {'name': 'Andrew', 'surname': 'Svetlov'} into template named "tmpl.jinja2" for getting resulting HTML text.

More complex template processing can be achieved by modifying the existing list of global functions. Modification of Jinja2’s environment can be done via get_env(). For example, adding the zip function:

env = aiohttp_jinja2.get_env(app)

Which can now to be used in any template:

{% for value, square in zip(values, squares) %}
    <p>The square of {{ value }} is {{ square }}.</p>
{% endfor %}

In some cases, finer control over the dataflow may also be required. This can be worked out by explicitly asking for template to be rendered using render_template(). Explicit rendering will allow to possibly pass some context to the renderer and also to modify its response on the fly. This can for example be used to set response headers:

async def handler(request):
    context = {'name': 'Andrew', 'surname': 'Svetlov'}
    response = aiohttp_jinja2.render_template('tmpl.jinja2',
    response.headers['Content-Language'] = 'ru'
    return response

This, again, can also be done with a class-based view (aiohttp.web.View):

class Handler(web.View):
    async def get(self):
        context = {'name': 'Andrew', 'surname': 'Svetlov'}
        response = aiohttp_jinja2.render_template('tmpl.jinja2',
        response.headers['Content-Language'] = 'ru'
        return response

Context processors is a way to add some variables to each template context. It works like jinja2.Environment().globals, but calculate variables each request. So if you need to add global constants it will be better to use jinja2.Environment().globals directly. But if you variables depends of request (e.g. current user) you have to use context processors.

Context processors is following last-win strategy. Therefore a context processor could rewrite variables delivered with previous one.

In order to use context processors create required processors:

async def foo_processor(request):
    return {'foo': 'bar'}

And pass them into setup():


As you can see, there is a built-in request_processor(), which adds current aiohttp.web.Request into context of templates under 'request' name.

Here is an example of how to add current user dependant logic to template (requires aiohttp_security library):

from aiohttp_security import authorized_userid

async def current_user_ctx_processor(request):
    userid = await authorized_userid(request)
    is_anonymous = not bool(userid)
    return {'current_user': {'is_anonymous': is_anonymous}}


        {% if current_user.is_anonymous %}
            <a href="{{ url('login') }}">Login</a>
        {% else %}
            <a href="{{ url('logout') }}">Logout</a>
        {% endif %}

Async functions

If you pass the enable_async parameter to the setup function, then you will need to use the async functions for rendering:

    app, enable_async=True,


async def handler(request):
    return await aiohttp_jinja2.render_template_async(
        'tmpl.jinja2', request)

The @aiohttp_jinja2.template decorator will work for both cases.

Default Globals

app is always made in templates via jinja2.Environment().globals:

    <h1>Welcome to {{ app['name'] }}</h1>

Two more helpers are also enabled by default: url and static.

url can be used with just a view name:

    <a href="{{ url('index') }}">Index Page</a>

Or with arguments:

    <a href="{{ url('user', id=123) }}">User Page</a>

A query can be added to the url with the special query_ keyword argument:

    <a href="{{ url('user', id=123, query_={'foo': 'bar'}) }}">User Page</a>

For a view defined by app.router.add_get('/user-profile/{id}/', user, name='user'), the above would give:

    <a href="/user-profile/123/?foo=bar">User Page</a>

This is useful as it would allow your static path to switch in deployment or testing with just one line.

The static function has similar usage, except it requires you to set app[aiohttp_jinja2.static_root_key].

app = web.Application()
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader("/path/to/templates/folder"))
app[aiohttp_jinja2.static_root_key] = "/static"

Then in the template:

<script src="{{ static('dist/main.js') }}"></script>

Would result in:

<script src="/static/dist/main.js"></script>

Both url and static can be disabled by passing default_helpers=False to aiohttp_jinja2.setup.

Library Installation

The aiohttp_jinja2 can be installed by pip:

$ pip3 install aiohttp_jinja2

Source code

The project is hosted on GitHub.

Please feel free to file an issue on bug tracker if you have found a bug or have some suggestion for library improvement.

The library uses Travis for Continuous Integration.


aiohttp_jinja2 is offered under the Apache 2 license.


Indices and tables



A modern and designer-friendly templating language for Python.



An endpoint that returns http response.