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

早过忘川 提交于 2019-12-10 22:17:57

问题


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?


回答1:


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?'


来源:https://stackoverflow.com/questions/12139029/how-to-access-context-variables-from-the-jinjas-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!