Skip to content
Myr

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

8 files+92 added−39 removed

modified:docs/templates.rst+26 added
376 unmodified lines
377378However the name after the `endblock` word must match the block name.379380381Block Nesting and Scope382~~~~~~~~~~~~~~~~~~~~~~~383384Blocks can be nested for more complex layouts. However per default blocks385may not access variables from outer scopes::386387 {% for item in seq %}388 <li>{% block loop_item %}{{ item }}{% endblock %}</li>389 {% endfor %}390391This example would output empty ``<li>`` items because `item` is unavailable392inside the block. The reason for this is that if the block is replaced by393a child template a variable would appear that was not defined in the block or394passed to the context.395396Starting with Jinja 2.2 you can explicitly specify that variables are397available in a block by setting the block to "scoped" by adding the `scoped`398modifier to a block declaration::399400 {% for item in seq %}401 <li>{% block loop_item scoped %}{{ item }}{% endblock %}</li>402 {% endfor %}403404 When overriding a block the `scoped` modifier does not have to be provided.405406407HTML Escaping408-------------409410When generating HTML from templates, there's always a risk that a variable will
829 unmodified lines
modified:jinja2/compiler.py+6 added-2 removed
781 unmodified lines
782 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 lines
modified:jinja2/environment.py+3 added-16 removed
13 unmodified lines
14from jinja2.lexer import get_lexer, TokenStream15from jinja2.parser import Parser16from jinja2.optimizer import optimize17from jinja2.compiler import generate18from jinja2.runtime import Undefined, Context18from jinja2.runtime import Undefined, new_context19from jinja2.exceptions import TemplateSyntaxError20from jinja2.utils import import_string, LRUCache, Markup, missing, \21 concat, consume22
622 unmodified lines
645 is passed as it to the context without adding the globals.646647 `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)651652 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 call
181 unmodified lines
modified:jinja2/nodes.py+1 added-1 removed
267 unmodified lines
268269270class Block(Stmt):271 """A node that represents a block."""272 fields = ('name', 'body')272 fields = ('name', 'body', 'scoped')273274275class Include(Stmt):276 """A node that represents the include tag."""
513 unmodified lines
modified:jinja2/parser.py+1 added
147 unmodified lines
148149 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 lines
modified:jinja2/runtime.py+45 added-20 removed
15 unmodified lines
16 TemplateNotFound171819# 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']2324
16 unmodified lines
41 """Simple args to unicode conversion and concatenation."""42 return concat(imap(unicode, seq))434445def 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)636465class TemplateReference(object):66 """The `self` in templates."""6768 def __init__(self, context):69 self.__context = context7071 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)7677 def __repr__(self):78 return '<%s %r>' % (79 self.__class__.__name__,80 self.__context.name81 )828384class 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 created
82 unmodified lines
170 elif getattr(__obj, 'environmentfunction', 0):171 args = (__self.environment,) + args172 return __obj(*args, **kwargs)173174 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)178179 def _all(meth):180 proxy = lambda self: getattr(self.get_all(), meth)()181 proxy.__doc__ = getattr(dict, meth).__doc__182 proxy.__name__ = meth
34 unmodified lines
217except ImportError:218 pass219220177class TemplateReference(object):178 """The `self` in templates."""179180 def __init__(self, context):181 self.__context = context182183 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)188189 def __repr__(self):190 return '<%s %r>' % (191 self.__class__.__name__,192 self.__context.name193 )194195221class BlockReference(object):222 """One block on a template reference."""223224 def __init__(self, name, context, stack, depth):
286 unmodified lines
modified:tests/test_inheritance.py+9 added
164 unmodified lines
165 'standard.html': '''166 {% block content %}&nbsp;{% endblock %}167 '''168 })).get_template("test.html").render().split() == [u'outer_box', u'my_macro']169170171def 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 lines
17 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.2223Version 2.1.124-------------25(Bugfix release)
84 unmodified lines