SvartalF
SvartalF

Reputation: 163

How to access context variables from the Jinja's Extension?

I'm using django+jinja2 via coffin, and I can't understand how to access the context variables in the extension. For example, I have this:

from coffin.shortcuts import render_to_response

def some_view(request):
    return render_to_response('template.html', {'a': 1})

class RenderFooExtension(Extension):
    tags = set(['render_foo'])

    def parse(self, parser):
        lineno = parser.stream.next().lineno

        # Some parsing process

        return nodes.Output([self.call_method('render'),]).set_lineno(lineno)

    def render(self):
        # TODO: I need to get here, for example, `a` object
        return ''

So I need to get a variable in the render method. How can I do it?

Upvotes: 2

Views: 1667

Answers (1)

SvartalF
SvartalF

Reputation: 163

Ok, my own answer.

Add a jinja2.nodes.Name('a', 'load') into a call_method of the Extension like this, and it will be loaded from the context.

class RenderFooExtension(Extension):
    tags = set(['render_foo'])

    def parse(self, parser):
        lineno = parser.stream.next().lineno

        args = [nodes.Name('a', 'load'),]

        return nodes.Output([self.call_method('render', args),]).set_lineno(lineno)

    def render(self, a):
        print 'Gotcha!', a
        return 'something useful?'

Upvotes: 4

Related Questions