帮助自定义 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
正如我所说,这就是现在在职的。我不确定的是为什么我需要在 parse()
中返回 nodes.CallBlock
,而不是 self.call_method()
(其中返回一个 nodes.Call
对象)。如果有人有任何见解——或者可以向我指出有关编写扩展的教程——请告诉我。
I've struggled to get this Jinja2 custom extension to work -- the docs weren't kidding when they said writing one was not for "civilians" -- and finally managed to arrive at this working code:
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
As I said, this is now working. What I'm unsure about is why I need to return nodes.CallBlock
in parse()
, rather than self.call_method()
(which returns a nodes.Call
object). If anyone has any insight -- or can point me to a tutorial on writing extensions -- please do let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原因是
parse()
期望返回一个语句节点,例如CallBlock
或Assign
。call_method()
返回一个表达式节点,您必须将其包装在CallBlock
中才能有一个语句。The reason is that
parse()
is expected to return a statement node, such asCallBlock
orAssign
.call_method()
returns an expression node, which you must wrap inCallBlock
to have a statement.