Can one compile or revert a portion of the Jinja2 AST?
For example, is it possible to call a function or method from jinja2.environment
or jinja2.compiler.generate
or some equivalent on a list of nodes extracted from within a template?
For example, given a template y.html
:
avant-tag
{% xyz %}
tag content {{ 3 + 5 }}
{% endxyz %}
apres-tag
and an extension y.py
:
# -*- coding: utf-8 -*-
from jinja2 import nodes, Environment, FileSystemLoader
from jinja2.ext import Extension
class YExtension(Extension):
tags = set(['y'])
def __init__(self, environment):
super(YExtension, self).__init__(environment)
def parse(self, parser):
tag = parser.stream.next()
body = parser.parse_statements(['name:endy'], drop_needle=True)
return nodes.Const("<!-- slurping: %s -->" % str(body))
env = Environment(
loader = FileSystemLoader('.'),
extensions = [YExtension],
)
print env.get_template('x.html').render()
Running python y.py
results in the expected output of:
avant-tag
<!-- slurping: [Output(nodes=[TemplateData(data=u'\n tag-content '),
Add(left=Const(value=3), right=Const(value=5)),
TemplateData(data=u'\n ')])] -->
sous-tag
In the parse
method, how can one either:
- compile
body
to unicode (i.e.tag-content 8
); or, alternatively - revert
body
to its original source (i.e.tag-content {{ 3 + 5 }}
).
As a matter of background, this question relates to two prior questions:
Thank you for reading.
Brian