Skip to content
Myr

used the new nodetransformer to make mitsuhiko happy

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Christoph Hack · committed by Christoph Hack · parent 5af9c55 · Browse files · 2 files+4 added−23 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+4 added−23 removed

  • other:+4 added−23 removed

2 files+4 added−23 removed

modified:jinja2/optimizer.py+2 added-21 removed
6 unmodified lines
78 * eliminating constant nodes9 * evaluating filters and macros on constant nodes10 * unroll loops on constant values11 * replace variables which are already known (because the doesn't11 * replace variables which are already known (because they doesn't12 change often and you want to prerender a template) with constants1314 After the optimation you will get a new, simplier template which can15 be saved again for later rendering. But even if you don't want to
7 unmodified lines
23from jinja2 import nodes24from jinja2.visitor import NodeVisitor, NodeTransformer252627class Optimizer(NodeVisitor):27class Optimizer(NodeTransformer):2829 def __init__(self, environment, context={}):30 self.environment = environment31 self.context = context3233 def visit_Output(self, node):34 node.nodes = [self.visit(n) for n in node.nodes]35 return node3637 def visit_Template(self, node):38 body = []39 for n in node.body:40 x = self.visit(n)41 if isinstance(x, list):42 body.extend(x)43 else:44 body.append(x)45 node.body = body46 return node4733 def visit_Filter(self, node):34 """Try to evaluate filters if possible."""35 try:36 x = self.visit(node.node).as_const()
24 unmodified lines
61 if node.name not in self.context:62 return node63 return nodes.Const(self.context[node.name])6480 def generic_visit(self, node, *args, **kwargs):81 NodeVisitor.generic_visit(self, node, *args, **kwargs)82 return node658466def optimize(node, environment):67 optimizer = Optimizer(environment)68 return optimizer.visit(node)
modified:test_optimizer.py+2 added-2 removed
6 unmodified lines
7ast = env.parse("""8 Hi {{ "<blub>"|e }},9 how are you?1011 {% for item in ('foo', 'bar', 'blub') %}12 {{ item }}11 {% for item in ('foo', 'bar', 'blub', '<42>') %}12 {{ item|e }}13 {% endfor %}14""")15print ast16print
6 unmodified lines