帮助自定义Jinja2扩展 [英] Help with custom Jinja2 Extension
问题描述
我一直在努力使这个Jinja2自定义扩展能够正常工作-当他们说写一个不适合平民"的文档时,他们并没有开玩笑-最终设法找到了这个工作代码:
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
正如我所说,这现在正在起作用.我不确定的是为什么我需要在parse()
中返回nodes.CallBlock
,而不是self.call_method()
(它返回一个nodes.Call
对象).如果有人有任何见识-或可以为我提供有关编写扩展程序的教程-请让我知道.
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.
推荐答案
原因是希望parse()
返回语句节点,例如CallBlock
或Assign
. call_method()
返回一个表达式节点,必须将其包装在CallBlock
中才能有一条语句.
The reason is that parse()
is expected to return a statement node, such as CallBlock
or Assign
. call_method()
returns an expression node, which you must wrap in CallBlock
to have a statement.
这篇关于帮助自定义Jinja2扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!