Added support for optional `scoped` modifier to blocks.
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 271a0eb · Browse files · 8 files·+92 added−39 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+92 added−39 removed
- tests:+9 added−0 removed
- other:+83 added−39 removed
Provenance
- Commit
74a0cd9- Tree
8868105- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
271a0eb
8 files changed+92 added−39 removed
modified:docs/templates.rst+26 added
376 unmodified lines377 378 However the name after the `endblock` word must match the block name.379 380 381+Block Nesting and Scope382+~~~~~~~~~~~~~~~~~~~~~~~383+384+Blocks can be nested for more complex layouts. However per default blocks385+may not access variables from outer scopes::386+387+ {% for item in seq %}388+ <li>{% block loop_item %}{{ item }}{% endblock %}</li>389+ {% endfor %}390+391+This example would output empty ``<li>`` items because `item` is unavailable392+inside the block. The reason for this is that if the block is replaced by393+a child template a variable would appear that was not defined in the block or394+passed to the context.395+396+Starting with Jinja 2.2 you can explicitly specify that variables are397+available in a block by setting the block to "scoped" by adding the `scoped`398+modifier to a block declaration::399+400+ {% for item in seq %}401+ <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>402+ {% endfor %}403+404+ When overriding a block the `scoped` modifier does not have to be provided.405+406+407 HTML Escaping408 -------------409 410 When generating HTML from templates, there's always a risk that a variable will829 unmodified linesmodified:jinja2/compiler.py+6 added-2 removed
781 unmodified lines782 if self.extends_so_far > 0:783 self.writeline('if parent_template is None:')784 self.indent()785 level += 1786+ if node.scoped:787+ context = 'context.derived(locals())'788+ else:789+ context = 'context'786- self.writeline('for event in context.blocks[%r][0](context):' %787- node.name, node)790+ self.writeline('for event in context.blocks[%r][0](%s):' % (791+ node.name, context), node)792 self.indent()793 self.simple_write('event', frame)794 self.outdent(level)795 701 unmodified linesmodified:jinja2/environment.py+3 added-16 removed
13 unmodified lines14 from jinja2.lexer import get_lexer, TokenStream15 from jinja2.parser import Parser16 from jinja2.optimizer import optimize17 from jinja2.compiler import generate18-from jinja2.runtime import Undefined, Context18+from jinja2.runtime import Undefined, new_context19 from jinja2.exceptions import TemplateSyntaxError20 from jinja2.utils import import_string, LRUCache, Markup, missing, \21 concat, consume22 622 unmodified lines645 is passed as it to the context without adding the globals.646 647 `locals` can be a dict of local variables for internal usage.648 """649- if vars is None:650- vars = {}651- if shared:652- parent = vars653- else:654- parent = dict(self.globals, **vars)655- if locals:656- # if the parent is shared a copy should be created because657- # we don't want to modify the dict passed658- if shared:659- parent = dict(parent)660- for key, value in locals.iteritems():661- if key[:2] == 'l_' and value is not missing:662- parent[key[2:]] = value663- return Context(self.environment, parent, self.name, self.blocks)649+ return new_context(self.environment, self.name, self.blocks,650+ vars, shared, self.globals, locals)651 652 def make_module(self, vars=None, shared=False, locals=None):653 """This method works like the :attr:`module` attribute when called654 without arguments but it will evaluate the template every call181 unmodified linesmodified:jinja2/nodes.py+1 added-1 removed
267 unmodified lines268 269 270 class Block(Stmt):271 """A node that represents a block."""272- fields = ('name', 'body')272+ fields = ('name', 'body', 'scoped')273 274 275 class Include(Stmt):276 """A node that represents the include tag."""513 unmodified linesmodified:jinja2/parser.py+1 added
147 unmodified lines148 149 def parse_block(self):150 node = nodes.Block(lineno=self.stream.next().lineno)151 node.name = self.stream.expect('name').value152+ node.scoped = self.stream.skip_if('name:scoped')153 node.body = self.parse_statements(('name:endblock',), drop_needle=True)154 self.stream.skip_if('name:' + node.name)155 return node156 627 unmodified linesmodified:jinja2/runtime.py+45 added-20 removed
15 unmodified lines16 TemplateNotFound17 18 19 # these variables are exported to the template runtime20-__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',20+__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',21 'TemplateRuntimeError', 'missing', 'concat', 'escape',22 'markup_join', 'unicode_join', 'TemplateNotFound']23 24 16 unmodified lines41 """Simple args to unicode conversion and concatenation."""42 return concat(imap(unicode, seq))43 44 45+def new_context(environment, template_name, blocks, vars=None,46+ shared=None, globals=None, locals=None):47+ """Internal helper to for context creation."""48+ if vars is None:49+ vars = {}50+ if shared:51+ parent = vars52+ else:53+ parent = dict(globals or (), **vars)54+ if locals:55+ # if the parent is shared a copy should be created because56+ # we don't want to modify the dict passed57+ if shared:58+ parent = dict(parent)59+ for key, value in locals.iteritems():60+ if key[:2] == 'l_' and value is not missing:61+ parent[key[2:]] = value62+ return Context(environment, parent, template_name, blocks)63+64+65+class TemplateReference(object):66+ """The `self` in templates."""67+68+ def __init__(self, context):69+ self.__context = context70+71+ def __getitem__(self, name):72+ blocks = self.__context.blocks[name]73+ wrap = self.__context.environment.autoescape and \74+ Markup or (lambda x: x)75+ return BlockReference(name, self.__context, blocks, 0)76+77+ def __repr__(self):78+ return '<%s %r>' % (79+ self.__class__.__name__,80+ self.__context.name81+ )82+83+84 class Context(object):85 """The template context holds the variables of a template. It stores the86 values passed to the template and also the names the template exports.87 Creating instances is neither supported nor useful as it's created82 unmodified lines170 elif getattr(__obj, 'environmentfunction', 0):171 args = (__self.environment,) + args172 return __obj(*args, **kwargs)173 174+ def derived(self, locals=None):175+ """Internal helper function to create a derived context."""176+ return new_context(self.environment, self.name, self.blocks,177+ self.parent, True, None, locals)178+179 def _all(meth):180 proxy = lambda self: getattr(self.get_all(), meth)()181 proxy.__doc__ = getattr(dict, meth).__doc__182 proxy.__name__ = meth34 unmodified lines217 except ImportError:218 pass219 220 177-class TemplateReference(object):178- """The `self` in templates."""179-180- def __init__(self, context):181- self.__context = context182-183- def __getitem__(self, name):184- blocks = self.__context.blocks[name]185- wrap = self.__context.environment.autoescape and \186- Markup or (lambda x: x)187- return BlockReference(name, self.__context, blocks, 0)188-189- def __repr__(self):190- return '<%s %r>' % (191- self.__class__.__name__,192- self.__context.name193- )194-195-221 class BlockReference(object):222 """One block on a template reference."""223 224 def __init__(self, name, context, stack, depth):286 unmodified linesmodified:tests/test_inheritance.py+9 added
164 unmodified lines165 'standard.html': '''166 {% block content %} {% endblock %}167 '''168 })).get_template("test.html").render().split() == [u'outer_box', u'my_macro']169+170+171+def test_scoped_block():172+ env = Environment(loader=DictLoader({173+ 'master.html': '{% for item in seq %}[{% block item scoped %}'174+ '{% endblock %}]{% endfor %}'175+ }))176+ t = env.from_string('{% extends "master.html" %}{% block item %}{{ item }}{% endblock %}')177+ assert t.render(seq=range(5)) == '[0][1][2][3][4]'modified:CHANGES+1 added
16 unmodified lines17 that were unused in the callers frame (#327)18 - Fixed a bug that caused internal errors if names where used as iteration19 variable and regular variable *after* the loop if that variable was unused20 *before* the loop. (#331)21+- Added support for optional `scoped` modifier to blocks.22 23 Version 2.1.124 -------------25 (Bugfix release)84 unmodified lines