How do I create a jinja2 extension?
You use CallBlock
which indicates that you want your extension to act like a block. For example.
{% mytest arg1 arg2 %}
stuff
in
here
{% endmytest %}
nodes.CallBlock
expects you to pass it a list of nodes representing the body (inner statements) for your extension. You are currently passing None
- hence your fault.
Once you have analyzed your arguments, you need to move on to analyzing the block body. Fortunately, this is easy. You can simply do:
body = parser.parse_statements(['name:endmytest'], drop_needle=True)
and then return the new node. CallBlock
gets a method to be called (in this case _mytestfunc
) that provides the logic for your extension.
body = parser.parse_statements(['name:endmytest'], drop_needle=True)
return nodes.CallBlock(self.call_method('_mytestfunc', args),[], [], body).set_lineno(lineno)
Alternatively, if you don't want your extension to be a block tag like
{% mytest arg1 arg2 %}
you shouldn't use nodes.CallBlock
, you should just use nodes.Call
instead, which doesn't take a body parameter. So simple:
return self.call_method('_mytestfunc', args)
self.call_method
is just a handy wrapper function that creates a call to node.
I've spent a few days writing Jinja2 extensions and it's hard. There isn't much documentation out there (other than code). The coffin GitHub project has some example extensions here .
source to share