aiohttp-jinja2

repository·master·Indexed 42 days ago

https://github.com/aio-libs/aiohttp-jinja2

A Jinja2 template renderer designed for the aiohttp.web framework. It provides a @template decorator for view functions, manual rendering via render_template() and render_string(), and support for asynchronous template rendering when enabled via setup().

Tokens
3.3K
Snippets
16
Records
18
Agent score
51%

What's inside aiohttp-jinja2

  1. Use Context Processors for request-dependent variables

    master

    Context processors allow you to inject variables into every template context. Unlike global variables, context processors can calculate values based on the current request (e.g., the current user).

    Note: Context processors follow a 'last-win' strategy, meaning later processors can overwrite variables from earlier ones. aiohttp_jinja2 provides a built-in request_processor which adds the current aiohttp.web.Request object to the template context under the name 'request'.

    # Define a processor
    async def foo_processor(request):
        return {'foo': 'bar'}
    
    # Register it during setup
    aiohttp_jinja2.setup(
        app,
        context_processors=[foo_processor, aiohttp_jinja2.request_processor],
        loader=loader)
  2. Setup aiohttp-jinja2 in an aiohttp application

    master

    To use aiohttp-jinja2, you must first initialize the Jinja2 environment within your aiohttp.web.Application using aiohttp_jinja2.setup(). You typically provide a loader (such as jinja2.FileSystemLoader) to specify where your templates are located.

    app = web.Application()
    aiohttp_jinja2.setup(app,
        loader=jinja2.FileSystemLoader('/path/to/templates/folder'))
  3. Render templates using the @aiohttp_jinja2.template decorator

    master

    The most convenient way to render templates is by using the @aiohttp_jinja2.template decorator on your web handlers. When a decorated handler returns a dictionary, that dictionary is automatically passed as the template context.

    # Function-based handler
    @aiohttp_jinja2.template('tmpl.jinja2')
    def handler(request):
        return {'name': 'Andrew', 'surname': 'Svetlov'}
    
    # Class-based view
    class Handler(web.View):
        @aiohttp_jinja2.template('tmpl.jinja2')
        async def get(self):
            return {'name': 'Andrew', 'surname': 'Svetlov'}
  4. Setup the Jinja2 environment in aiohttp

    master

    Before rendering templates, you must initialize the Jinja2 environment within your aiohttp.web.Application instance using aiohttp_jinja2.setup(). You typically provide a loader (such as jinja2.FileSystemLoader) to specify where your template files are located.

    import aiohttp_jinja2
    import jinja2
    from aiohttp import web
    
    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('/path/to/templates/folder'))
  5. Use the @aiohttp_jinja2.template decorator

    master

    The most convenient way to render templates is by using the @aiohttp_jinja2.template decorator on your web handlers. When the handler returns a dictionary, the decorator automatically passes that dictionary as the template context and returns the rendered response.

    Function-based handlers

    @aiohttp_jinja2.template('tmpl.jinja2')
    def handler(request):
        return {'name': 'Andrew', 'surname': 'Svetlov'}

    Class-based views

    class Handler(web.View):
        @aiohttp_jinja2.template('tmpl.jinja2')
        async def get(self):
            return {'name': 'Andrew', 'surname': 'Svetlov'}
  6. Render templates manually with render_template()

    master

    If you need to render a template within a view function manually, use aiohttp_jinja2.render_template(). This function returns a response object.

    Parameters:

    • template_name: The name of the template to render.
    • request: The current aiohttp.web.Request object.
    • context: A dictionary of variables to pass to the template.
    • app_key: The key to access the environment (defaults to 'aiohttp_jinja2_environment').
    • encoding: The response charset (defaults to 'utf-8').
    • status: The HTTP status code (defaults to 200).
    import aiohttp_jinja2
    
    async def handler(request):
        context = {'foo': 'bar'}
        response = aiohttp_jinja2.render_template('tmpl.jinja2', request, context)
        return response
    
    app.router.add_get('/tmpl', handler)
  7. Render template strings with render_string()

    master

    Use aiohttp_jinja2.render_string() to render a raw template string and return the resulting string.

    Parameters:

    • template_name: The template string to render.
    • request: The aiohttp.web.Request object.
    • context: The dictionary used as template context.
    • app_key: The key to access the environment (defaults to 'aiohttp_jinja2_environment').

    Note: If enable_async=True was passed to setup(), you should use render_string_async() instead.

  8. Modify the Jinja2 environment using get_env

    master

    If you need to add global functions or modify the Jinja2 environment (e.g., adding a zip function), use aiohttp_jinja2.get_env(app) to retrieve the environment object.

    env = aiohttp_jinja2.get_env(app)
    env.globals.update(zip=zip)
  9. Use the @template decorator for view functions

    master

    The @aiohttp_jinja2.template decorator can be applied to both synchronous and asynchronous view functions. Instead of returning a response object, the decorated function should return a dictionary representing the template context. The decorator then handles rendering the specified template and returning the response.

    Parameters:

    • template_name: The name of the template file (raises 500 if not found).
    • app_key: The key to access the environment from the application (defaults to 'aiohttp_jinja2_environment').
    • encoding: The charset for the response (defaults to 'utf-8').
    • status: The HTTP status code for the response (defaults to 200).
    import aiohttp_jinja2
    
    @aiohttp_jinja2.template('tmpl.jinja2')
    async def handler(request):
        context = {'foo': 'bar'}
        return context
    
    app.router.add_get('/tmpl', handler)
  10. Enable asynchronous template rendering

    master

    If you pass enable_async=True to the setup function, you must use the asynchronous rendering function render_template_async. The @aiohttp_jinja2.template decorator remains compatible with both sync and async modes.

    aiohttp_jinja2.setup(app, enable_async=True, loader=loader)
    
    async def handler(request):
        return await aiohttp_jinja2.render_template_async('tmpl.jinja2', request)