[Django]-How to get access to context from Jinja2 extension

0👍

You can use the contextfunction wrapper.

from jinja2 import contextfunction

class get_metadata(Extension):
    tags = {'get_metadata'}

    def parse(self, parser):
        while not parser.stream.current.type == 'block_end':
            parser.stream.next()
        return nodes.Output([self.call_method('_get_metadata')])

    @contextfunction
    def _get_metadata(self, context):
        req = context.get("request")
        if not req:
            return None
        return req["META"]["PATH_INFO"]

register = CoffinLibrary()
register.tag(get_metadata)

Leave a comment