imports and includes "with context" are passed the full context now, not only the initial one.
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 7966895 · Browse files · 5 files·+62 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+62 added−16 removed
- tests:+8 added−0 removed
- other:+54 added−16 removed
Provenance
- Commit
673aa88- Tree
b852c47- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
7966895
5 files changed+62 added−16 removed
modified:docs/templates.rst+13 added
792 unmodified lines793 794 {% from 'forms.html' import input with context %}795 {% include 'header.html' without context %}796 797+.. admonition:: Note798 799+ In Jinja 2.0 the context that was passed to the included template800+ did not include variables define in the template. As a matter of801+ fact this did not work::802+803+ {% for box in boxes %}804+ {% include "render_box.html" %}805+ {% endfor %}806+807+ The included template ``render_box.html`` is not able to access808+ `box` in Jinja 2.0, but in Jinja 2.1.809+810+811 .. _expressions:812 813 Expressions814 -----------327 unmodified linesmodified:jinja2/compiler.py+25 added-9 removed
518 unmodified lines519 mapping[name] = self.temporary_identifier()520 self.writeline('%s = environment.%s[%r]' %521 (mapping[name], dependency, name))522 523- def collect_shadowed(self, frame, extra_vars=()):523+ def push_scope(self, frame, extra_vars=()):524 """This function returns all the shadowed variables in a dict525 in the form name: alias and will write the required assignments526 into the current scope. No indentation takes place.527 528+ This also predefines locally declared variables from the loop529+ body because under some circumstances it may be the case that530+531 `extra_vars` is passed to `Identifiers.find_shadowed`.532 """533 aliases = {}534 for name in frame.identifiers.find_shadowed(extra_vars):535 aliases[name] = ident = self.temporary_identifier()536 self.writeline('%s = l_%s' % (ident, name))537+ to_declare = set()538+ for name in frame.identifiers.declared_locally:539+ if name not in aliases:540+ to_declare.add('l_' + name)541+ if to_declare:542+ self.writeline(' = '.join(to_declare) + ' = missing')543 return aliases544 536- def restore_shadowed(self, aliases):537- """Restore all aliases."""545+ def pop_scope(self, aliases, frame):546+ """Restore all aliases and delete unused variables."""547 for name, alias in aliases.iteritems():548 self.writeline('l_%s = %s' % (name, alias))549+ to_delete = set()550+ for name in frame.identifiers.declared_locally:551+ if name not in aliases:552+ to_delete.add('l_' + name)553+ if to_delete:554+ self.writeline('del ' + ', '.join(to_delete))555 556 def function_scoping(self, node, frame, children=None,557 find_special=True):558 """In Jinja a few statements require the help of anonymous261 unmodified lines820 self.writeline('template = environment.get_template(', node)821 self.visit(node.template, frame)822 self.write(', %r)' % self.name)823 self.writeline('for event in template.root_render_func('809- 'template.new_context(context.parent, True)):')824+ 'template.new_context(context.parent, True, '825+ 'locals())):')826 else:827 self.writeline('for event in environment.get_template(', node)828 self.visit(node.template, frame)829 self.write(', %r).module._body_stream:' %10 unmodified lines840 self.write('environment.get_template(')841 self.visit(node.template, frame)842 self.write(', %r).' % self.name)843 if node.with_context:828- self.write('make_module(context.parent, True)')844+ self.write('make_module(context.parent, True, locals())')845 else:846 self.write('module')847 if frame.toplevel and not node.target.startswith('_'):848 self.writeline('context.exported_vars.discard(%r)' % node.target)71 unmodified lines920 # if we don't have an recursive loop we have to find the shadowed921 # variables at that point. Because loops can be nested but the loop922 # variable is a special one we have to enforce aliasing for it.923 if not node.recursive:908- aliases = self.collect_shadowed(loop_frame, ('loop',))924+ aliases = self.push_scope(loop_frame, ('loop',))925 926 # otherwise we set up a buffer and add a function def927 else:928 self.writeline('def loop(reciter, loop_render_func):', node)80 unmodified lines1009 self.blockvisit(node.else_, loop_frame)1010 self.outdent()1011 1012 # reset the aliases if there are any.997- self.restore_shadowed(aliases)1013+ self.pop_scope(aliases, loop_frame)1014 1015 # if the node was recursive we have to return the buffer contents1016 # and start the iteration code1017 if node.recursive:40 unmodified lines1058 1059 def visit_FilterBlock(self, node, frame):1060 filter_frame = frame.inner()1061 filter_frame.inspect(node.iter_child_nodes())1046- aliases = self.collect_shadowed(filter_frame)1062+ aliases = self.push_scope(filter_frame)1063 self.pull_locals(filter_frame)1064 self.buffer(filter_frame)1065 self.blockvisit(node.body, filter_frame)1066 self.start_write(frame, node)1067 self.visit_Filter(node.filter, filter_frame)1068 self.end_write(frame)1053- self.restore_shadowed(aliases)1069+ self.pop_scope(aliases, filter_frame)1070 1071 def visit_ExprStmt(self, node, frame):1072 self.newline(node)1073 self.visit(node.node, frame)368 unmodified linesmodified:jinja2/environment.py+13 added-7 removed
577 unmodified lines578 from jinja2.debug import translate_exception579 exc_type, exc_value, tb = translate_exception(sys.exc_info())580 raise exc_type, exc_value, tb581 582- def new_context(self, vars=None, shared=False):582+ def new_context(self, vars=None, shared=False, locals=None):583 """Create a new :class:`Context` for this template. The vars584 provided will be passed to the template. Per default the globals585- are added to the context, if shared is set to `True` the data586- provided is used as parent namespace. This is used to share the587- same globals in multiple contexts without consuming more memory.588- (This works because the context does not modify the parent dict)585+ are added to the context. If shared is set to `True` the data586+ is passed as it to the context without adding the globals.587+588+ `locals` can be a dict of local variables for internal usage.589 """590 if vars is None:591 vars = {}592 if shared:593 parent = vars594 else:595 parent = dict(self.globals, **vars)596+ if locals:597+ if shared:598+ parent = dict(parent)599+ for key, value in locals.iteritems():600+ if key[:2] == 'l_' and value is not missing:601+ parent[key[2:]] = value602 return Context(self.environment, parent, self.name, self.blocks)603 598- def make_module(self, vars=None, shared=False):604+ def make_module(self, vars=None, shared=False, locals=None):605 """This method works like the :attr:`module` attribute when called606 without arguments but it will evaluate the template every call607 rather then caching the template. It's also possible to provide608 a dict which is then used as context. The arguments are the same609 as for the :meth:`new_context` method.610 """605- return TemplateModule(self, self.new_context(vars, shared))611+ return TemplateModule(self, self.new_context(vars, shared, locals))612 613 @property614 def module(self):615 """The template as module. This is used for imports in the153 unmodified linesmodified:tests/test_imports.py+8 added
38 unmodified lines39 t = test_env.from_string('{% include "header" without context %}')40 assert t.render(foo=42) == '[|23]'41 42 43+def test_context_include_with_overrides():44+ env = Environment(loader=DictLoader(dict(45+ main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",46+ item="{{ item }}"47+ )))48+ assert env.get_template("main").render() == "123"49+50+51 def test_trailing_comma():52 test_env.from_string('{% from "foo" import bar, baz with context %}')53 test_env.from_string('{% from "foo" import bar, baz, with context %}')54 test_env.from_string('{% from "foo" import bar, with context %}')17 unmodified linesmodified:CHANGES+3 added
32 unmodified lines33 - implemented a bytecode cache system. (:ref:`bytecode-cache`)34 35 - the template context is now weakref-able36 37+- inclusions and imports "with context" forward all variables now, not only38+ the initial context.39+40 Version 2.041 -----------42 (codename jinjavitus, released on July 17th 2008)43 32 unmodified lines