From 65642a52312690f6743aead65c9634ee6bb7c9b0 Mon Sep 17 00:00:00 2001 From: Christoph Hack Date: Tue, 8 Apr 2008 14:46:56 +0200 Subject: [PATCH] added environment, make filters available locally --HG-- branch : trunk --- jinja2/compiler.py | 20 ++++++++++++++++---- test.py | 2 +- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/jinja2/compiler.py b/jinja2/compiler.py index 41577c8..95d2f35 100644 --- a/jinja2/compiler.py +++ b/jinja2/compiler.py @@ -29,9 +29,9 @@ operators = { } -def generate(node, filename, stream=None): +def generate(node, environment, filename, stream=None): is_child = node.find(nodes.Extends) is not None - generator = CodeGenerator(is_child, filename, stream) + generator = CodeGenerator(environment, is_child, filename, stream) generator.visit(node) if stream is None: return generator.stream.getvalue() @@ -56,6 +56,10 @@ class Identifiers(object): # names that are declared by parameters self.declared_parameter = set() + # filters that are declared locally + self.declared_filter = set() + self.undeclared_filter = set() + def add_special(self, name): """Register a special name like `loop`.""" self.undeclared.discard(name) @@ -117,6 +121,11 @@ class FrameIdentifierVisitor(NodeVisitor): if not self.identifiers.is_declared(node.name): self.identifiers.undeclared.add(node.name) + def visit_FilterCall(self, node): + if not node.name in self.identifiers.declared_filter: + self.identifiers.undeclared_filter.add(node.name) + self.identifiers.declared_filter.add(node.name) + def visit_Macro(self, node): """Macros set local.""" self.identifiers.declared_locally.add(node.name) @@ -128,9 +137,10 @@ class FrameIdentifierVisitor(NodeVisitor): class CodeGenerator(NodeVisitor): - def __init__(self, is_child, filename, stream=None): + def __init__(self, environment, is_child, filename, stream=None): if stream is None: stream = StringIO() + self.environment = environment self.is_child = is_child self.filename = filename self.stream = stream @@ -205,6 +215,8 @@ class CodeGenerator(NodeVisitor): self.indent() for name in frame.identifiers.undeclared: self.writeline('l_%s = context[%r]' % (name, name)) + for name in frame.identifiers.undeclared_filter: + self.writeline('f_%s = context[%r]' % (name, name)) if not no_indent: self.outdent() @@ -516,7 +528,7 @@ class CodeGenerator(NodeVisitor): def visit_Filter(self, node, frame): for filter in node.filters: - self.write('context.filters[%r](' % filter.name) + self.write('f_%s(' % filter.name) self.visit(node.node, frame) for filter in reversed(node.filters): self.signature(filter, frame) diff --git a/test.py b/test.py index 7b5d78e..68ed7b8 100644 --- a/test.py +++ b/test.py @@ -14,4 +14,4 @@ ast = env.parse(""" """) print ast print -print generate(ast, "foo.html") +print generate(ast, env, "foo.html") -- 2.26.2