帮助定制Jinja2扩展

dcr*_*sta 10 python jinja2

我一直在努力让这个Jinja2定制扩展工作 - 当他们说写一个不是为了"平民"时,文档并不是在开玩笑 - 最后设法得到了这个工作代码:

class WrapperExtension(Extension):

    tags = set(['wrap'])

    def parse(self, parser):
        lineno = parser.stream.next().lineno
        args = [parser.parse_expression()]
        args.append(nodes.Const(args[0].name))
        return nodes.CallBlock(
            self.call_method('_render', args),
            [], [], []).set_lineno(lineno)

    def _render(self, value, name, *args, **kwargs):
        if some_condition():
            return '<wrapper id="%s">%s</wrapper>' % (name, value)
        return value
Run Code Online (Sandbox Code Playgroud)

正如我所说,这现在正在发挥作用.什么我不确定就是为什么我需要返回nodes.CallBlockparse(),而不是self.call_method()(它返回一个nodes.Call对象).如果有人有任何见解 - 或者可以指向我编写扩展的教程 - 请告诉我.

Ben*_*son 4

原因是parse()期望返回一个语句节点,例如CallBlockor Assigncall_method()返回一个表达式节点,您必须将其包装起来CallBlock才能有一个语句。