From: Christoph Hack Date: Tue, 8 Apr 2008 21:17:27 +0000 (+0200) Subject: added subscribe-optimation X-Git-Tag: 2.0rc1~203^2 X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=ca0666d874d7cb2d9aae2591bed88d50f96b95fb;p=jinja2.git added subscribe-optimation --HG-- branch : trunk --- diff --git a/jinja2/optimizer.py b/jinja2/optimizer.py index c9787f6..e7f6ac7 100644 --- a/jinja2/optimizer.py +++ b/jinja2/optimizer.py @@ -22,6 +22,7 @@ from copy import deepcopy from jinja2 import nodes from jinja2.visitor import NodeVisitor, NodeTransformer +from jinja2.runtime import subscribe class Optimizer(NodeTransformer): @@ -62,7 +63,16 @@ 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) diff --git a/test_optimizer.py b/test_optimizer.py index e23d862..06ee440 100644 --- a/test_optimizer.py +++ b/test_optimizer.py @@ -4,19 +4,24 @@ from jinja2.optimizer import optimize env = Environment() +forums = [ + {'id': 1, 'name': u'Example'}, + {'id': 2, 'name': u'Foobar'}, + {'id': 3, 'name': u'<42>'} +] ast = env.parse(""" Hi {{ ""|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")