Skip to content
Myr

revamped jinja2 import system. the behavior is less confusing now, but it's not backwards compatible. I like it though ;)

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

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 6ce170c · Browse files · 8 files+125 added−60 removed
This commit

State

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

Diff stats

8 files+125 added−60 removed

  • tests:+0 added−6 removed
  • other:+125 added−54 removed

8 files+125 added−60 removed

modified:jinja2/compiler.py+42 added-32 removed
208 unmodified lines
209 self.generic_visit(node)210 self.identifiers.tests.add(node.name)211212 def visit_Macro(self, node):213 """Macros set local."""213 self.identifiers.declared_locally.add(node.name)214216 def visit_Include(self, node):217 """Some includes set local."""215 def visit_Import(self, node):216 self.generic_visit(node)219 if node.target is not None:220 self.identifiers.declared_locally.add(node.target)217 self.identifiers.declared_locally.add(node.target)218219 def visit_FromImport(self, node):220 self.generic_visit(node)221 self.identifiers.declared_locally.update(node.names)222223 def visit_Assign(self, node):224 """Visit assignments in the correct order."""225 self.visit(node.node)226 self.visit(node.target)
5 unmodified lines
232233class CompilerExit(Exception):234 """Raised if the compiler encountered a situation where it just235 doesn't make sense to further process the code. Any block that235 raises such an exception is not further processed."""236 raises such an exception is not further processed.237 """238239240class CodeGenerator(NodeVisitor):241
356 unmodified lines
598 self.extends_so_far += 1599600 def visit_Include(self, node, frame):601 """Handles includes."""600 # simpled include is include into a variable. This kind of601 # include works the same on every level, so we handle it first.602 if node.target is not None:603 self.writeline('l_%s = ' % node.target, node)604 if frame.toplevel:605 self.write('context[%r] = ' % node.target)606 self.write('environment.get_template(')607 self.visit(node.template, frame)608 self.write(', %r).include(context)' % self.name)609 return610602 self.writeline('included_template = environment.get_template(', node)603 self.visit(node.template, frame)604 self.write(', %r)' % self.name)614 if frame.toplevel:615 self.writeline('included_context = included_template.new_context('616 'context.get_root())')617 self.writeline('for event in included_template.root_render_func('618 'included_context):')619 else:620 self.writeline('for event in included_template.root_render_func('621 'included_template.new_context(context.get_root())):')605 self.writeline('for event in included_template.root_render_func('606 'included_template.new_context(context.get_root())):')607 self.indent()608 if frame.buffer is None:609 self.writeline('yield event')610 else:611 self.writeline('%s.append(event)' % frame.buffer)612 self.outdent()613629 # if we have a toplevel include the exported variables are copied630 # into the current context without exporting them. context.udpate631 # does *not* mark the variables as exported614 def visit_Import(self, node, frame):615 """Visit regular imports."""616 self.writeline('l_%s = ' % node.target, node)617 if frame.toplevel:633 self.writeline('context.update(included_context.get_exported())')618 self.write('context[%r] = ' % node.target)619 self.write('environment.get_template(')620 self.visit(node.template, frame)621 self.write(', %r).include(context)' % self.name)622623 def visit_FromImport(self, node, frame):624 """Visit named imports."""625 self.newline(node)626 self.write('included_template = environment.get_template(')627 self.visit(node.template, frame)628 self.write(', %r).include(context)' % self.name)629 for name in node.names:630 self.writeline('l_%s = getattr(included_template, '631 '%r, missing)' % (name, name))632 self.writeline('if l_%s is missing:' % name)633 self.indent()634 self.writeline('l_%s = environment.undefined(%r %% '635 'included_template.name)' %636 (name, 'the template %r does not export '637 'the requested name ' + repr(name)))638 self.outdent()639 if frame.toplevel:640 self.writeline('context[%r] = l_%s' % (name, name))641642 def visit_For(self, node, frame):643 loop_frame = frame.inner()644 loop_frame.inspect(node.iter_child_nodes())645 extended_loop = bool(node.else_) or \
382 unmodified lines
10281029 def visit_Filter(self, node, frame, initial=None):1030 self.write('f_%s(' % node.name)1031 func = self.environment.filters.get(node.name)1032 if func is None:1033 raise TemplateAssertionError('no filter named %r' % node.name,1034 node.lineno, self.filename)1035 if getattr(func, 'contextfilter', False):1036 self.write('context, ')1037 elif getattr(func, 'environmentfilter', False):1038 self.write('environment, ')
7 unmodified lines
1046 self.write(')')10471048 def visit_Test(self, node, frame):1049 self.write('t_%s(' % node.name)1040 func = self.environment.tests.get(node.name)1041 if getattr(func, 'contexttest', False):1042 self.write('context, ')1050 if node.name not in self.environment.tests:1051 raise TemplateAssertionError('no test named %r' % node.name,1052 node.lineno, self.filename)1053 self.visit(node.node, frame)1054 self.signature(node, frame)1055 self.write(')')1056
29 unmodified lines
modified:jinja2/filters.py+2 added-1 removed
631 unmodified lines
632 'abs': abs,633 'round': do_round,634 'sort': do_sort,635 'groupby': do_groupby,636 'safe': Markup636 'safe': Markup,637 'xmlattr': do_xmlattr638}
modified:jinja2/lexer.py+2 added-1 removed
35 unmodified lines
36# set of used keywords37keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',38 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',39 'extends', 'filter', 'for', 'if', 'in', 'include',40 'is', 'macro', 'not', 'or', 'raw', 'call', 'endcall'])40 'is', 'macro', 'not', 'or', 'raw', 'call', 'endcall',41 'from', 'import'])4243# bind operators to token types44operators = {45 '+': 'add',
388 unmodified lines
modified:jinja2/nodes.py+17 added
261 unmodified lines
262263264class Include(Stmt):265 """A node that represents the include tag."""266 fields = ('template',)267268269class Import(Stmt):270 """A node that represents the import tag."""271 fields = ('template', 'target')272273274class FromImport(Stmt):275 """A node that represents the from import tag. It's important to not276 pass unsafe names to the name attribute. The compiler translates the277 attribute lookups directly into getattr calls and does *not* use the278 subscribe callback of the interface. As exported variables may not279 start with double underscores (which the parser asserts) this is not a280 problem for regular Jinja code, but if this node is used in an extension281 extra care must be taken.282 """283 fields = ('template', 'names')284285286class Trans(Stmt):287 """A node for translatable sections."""288 fields = ('singular', 'plural', 'indicator', 'replacements')289
327 unmodified lines
modified:jinja2/optimizer.py+11 added
171 unmodified lines
172 except nodes.Impossible:173 return node174 return result175176 def visit_Import(self, node, context):177 rv = self.generic_visit(node, context)178 context.undef(node.target)179 return rv180181 def visit_FromImport(self, node, context):182 rv = self.generic_visit(node, context)183 for name in node.names:184 context.undef(name)185 return rv186187 def fold(self, node, context):188 """Do constant folding."""189 node = self.generic_visit(node, context)190 try:
11 unmodified lines
modified:jinja2/parser.py+44 added-18 removed
12 unmodified lines
13from jinja2.exceptions import TemplateSyntaxError141516_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',17 'macro', 'include'])17 'macro', 'include', 'from', 'import'])18_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])19statement_end_tokens = set(['variable_end', 'block_end', 'in'])20_tuple_edge_tokens = set(['rparen']) | statement_end_tokens21
122 unmodified lines
144 return node145146 def parse_include(self):147 node = nodes.Include(lineno=self.stream.expect('include').lineno)148 expr = self.parse_expression()149 if self.stream.current.type is 'assign':148 node.template = self.parse_expression()149 return node150151 def parse_import(self):152 node = nodes.Import(lineno=self.stream.expect('import').lineno)153 node.template = self.parse_expression()154 self.stream.expect('name:as')155 node.target = self.stream.expect('name').value156 if not nodes.Name(node.target, 'store').can_assign():157 raise TemplateSyntaxError('can\'t assign imported template '158 'to %r' % node.target, node.lineno,159 self.filename)160 return node161162 def parse_from(self):163 node = nodes.FromImport(lineno=self.stream.expect('from').lineno)164 node.template = self.parse_expression()165 self.stream.expect('import')166 node.names = []167 while 1:168 if node.names:169 self.stream.expect('comma')170 if self.stream.current.type is 'name':171 target = nodes.Name(self.stream.current.value, 'store')172 if not target.can_assign():173 raise TemplateSyntaxError('can\'t import object named %r'174 % target.name, target.lineno,175 self.filename)176 elif target.name.startswith('__'):177 raise TemplateAssertionError('names starting with two '178 'underscores can not be '179 'imported', target.lineno,180 self.filename)181 node.names.append(target.name)182 self.stream.next()183 if self.stream.current.type is not 'comma':184 break185 else:186 break187 if self.stream.current.type is 'comma':188 self.stream.next()151 if not isinstance(expr, nodes.Name):152 raise TemplateSyntaxError('must assign imported template to '153 'variable or current scope',154 expr.lineno, self.filename)155 if not expr.can_assign():156 raise TemplateSyntaxError('can\'t assign imported template '157 'to %r' % expr, expr.lineno,158 self.filename)159 node.target = expr.name160 node.template = self.parse_expression()161 else:162 node.target = None163 node.template = expr189 return node190191 def parse_signature(self, node):192 node.args = args = []
399 unmodified lines
592 if self.stream.current.type is 'name' and \593 self.stream.look().type is 'assign':594 key = self.stream.current.value595 self.stream.skip(2)596 value = self.parse_expression()571 kwargs.append(nodes.Keyword(key, self.parse_expression(),572 lineno=key.lineno))597 kwargs.append(nodes.Keyword(key, value,598 lineno=value.lineno))599 else:600 ensure(not kwargs)601 args.append(self.parse_expression())602
90 unmodified lines
modified:jinja2/runtime.py+7 added-2 removed
12 unmodified lines
13from jinja2.exceptions import UndefinedError141516__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',17 'Macro', 'Markup']17 'Macro', 'Markup', 'missing']181920# special singleton representing missing values for the runtime21missing = object()222324class TemplateContext(object):25 """Holds the variables of the local template or of the global one. It's26 not save to use this class outside of the compiled code. For example27 update and other methods will not work as they seem (they don't update
44 unmodified lines
72 self.vars.update(mapping)7374 def get_exported(self):75 """Get a new dict with the exported variables."""72 return dict((k, self.vars[k]) for k in self.exported_vars)76 return dict((k, self.vars[k]) for k in self.exported_vars77 if not k.startswith('__'))7879 def get_root(self):80 """Return a new dict with all the non local variables."""81 return dict(self.parent)
264 unmodified lines
modified:tests/test_syntax.py-6 removed
12 unmodified lines
13CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''14SLICING = '''{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}'''15ATTR = '''{{ foo.bar }}|{{ foo['bar'] }}'''16SUBSCRIPT = '''{{ foo[0] }}|{{ foo[-1] }}'''17KEYATTR = '''{{ {'items': 'foo'}.items }}|{{ {}.items() }}'''17TUPLE = '''{{ () }}|{{ (1,) }}|{{ (1, 2) }}'''18MATH = '''{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}'''19DIV = '''{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}'''20UNARY = '''{{ +3 }}|{{ -3 }}'''
41 unmodified lines
62 tmpl = env.from_string(SUBSCRIPT)63 assert tmpl.render(foo=[0, 1, 2]) == '0|2'646567def test_keyattr(env):68 tmpl = env.from_string(KEYATTR)69 assert tmpl.render() == 'foo|[]'707166def test_tuple(env):67 tmpl = env.from_string(TUPLE)68 assert tmpl.render() == '()|(1,)|(1, 2)'69
93 unmodified lines