4

I have a node for a Django template:

class MetadataNode(template.Node):
    def render(self, context):
    ...

Which register a tag:

def get_metadata(parser, token):
    ...
register = template.Library()
register.tag(get_metadata)

But I use a Jinja2 templates, therefore I need a Jinja2 extension:

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')])

    def _get_metadata(self):
        return Markup(MetadataNode().render(<Django context???>))

register = CoffinLibrary()
register.tag(get_metadata)

How to get access to Django context (particularity request.META.PATH_INFO) in parse method? Or how to run a render MetadataNode with context?

TyVik
  • 53
  • 7
  • In general, I was not able to make it through the extension of jinja2. I registered a function: from coffin.template import Library as CoffinLibrary from jinja2 import Markup def get_metadata(path_info): return Markup(some_python_function(path_info)) register = CoffinLibrary() register.object('get_metadata', get_metadata)` and execute it in template: `{{ get_metadata(request.META.PATH_INFO) }}` – TyVik Oct 02 '13 at 11:00
  • 1
    This question seems similar: http://stackoverflow.com/questions/12139029/how-to-access-context-variables-from-the-jinjas-extension – raacer Oct 22 '13 at 23:39

1 Answers1

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)
Dash2TheDot
  • 109
  • 1
  • 5