from copy import deepcopy
from jinja2 import nodes
from jinja2.visitor import NodeVisitor, NodeTransformer
+from jinja2.runtime import subscribe
class Optimizer(NodeTransformer):
return node
return nodes.Const(self.context[node.name])
+ def visit_Subscript(self, node):
+ try:
+ item = self.visit(node.node).as_const()
+ arg = self.visit(node.arg).as_const()
+ except nodes.Impossible:
+ return node
+ # XXX: what does the 3rd parameter mean?
+ return nodes.Const(subscribe(item, arg, None))
+
-def optimize(node, environment):
- optimizer = Optimizer(environment)
+def optimize(node, environment, context={}):
+ optimizer = Optimizer(environment, context=context)
return optimizer.visit(node)
env = Environment()
+forums = [
+ {'id': 1, 'name': u'Example'},
+ {'id': 2, 'name': u'Foobar'},
+ {'id': 3, 'name': u'<42>'}
+]
ast = env.parse("""
Hi {{ "<blub>"|e }},
how are you?
- {% for item in ('foo', 'bar', 'blub', '<42>') %}
- {{ item|e }}
+ {% for forum in forums %}
+ {{ readstatus(forum.id) }} {{ forum.id|e }} {{ forum.name|e }}
{% endfor %}
""")
print ast
print
print generate(ast, env, "foo.html")
print
-ast = optimize(ast, env)
+ast = optimize(ast, env, context={'forums': forums})
print ast
print
print generate(ast, env, "foo.html")