implemented includes
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 41ef36f · Browse files · 5 files·+118 added−22 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+118 added−22 removed
- other:+118 added−22 removed
Provenance
- Commit
f059ec1- Tree
09179f9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
41ef36f
5 files changed+118 added−22 removed
modified:jinja2/compiler.py+65 added-11 removed
77 unmodified lines78 79 # names that are declared by parameters80 self.declared_parameter = set()81 82- # filters that are referenced82+ # filters/tests that are referenced83 self.filters = set()84+ self.tests = set()85 86 def add_special(self, name):87 """Register a special name like `loop`."""88 self.undeclared.discard(name)77 unmodified lines166 self.identifiers.undeclared.add(node.name)167 168 def visit_Filter(self, node):169 self.generic_visit(node)169- if node.name not in self.identifiers.filters:170- self.identifiers.filters.add(node.name)170+ self.identifiers.filters.add(node.name)171 172+ def visit_Test(self, node):173+ self.generic_visit(node)174+ self.identifiers.tests.add(node.name)175+176 def visit_Macro(self, node):177 """Macros set local."""178 self.identifiers.declared_locally.add(node.name)179 180+ def visit_Include(self, node):181+ """Some includes set local."""182+ self.generic_visit(node)183+ if node.target is not None:184+ self.identifiers.declared_locally.add(node.target)185+186 def visit_Assign(self, node):187 """Visit assignments in the correct order."""188 self.visit(node.node)189 self.visit(node.target)95 unmodified lines285 for name in frame.identifiers.undeclared:286 self.writeline('l_%s = context[%r]' % (name, name))287 for name in frame.identifiers.filters:288 self.writeline('f_%s = environment.filters[%r]' % (name, name))289+ for name in frame.identifiers.tests:290+ self.writeline('t_%s = environment.tests[%r]' % (name, name))291 if not no_indent:292 self.outdent()293 294 # -- Visitors15 unmodified lines310 self.filename)311 self.blocks[block.name] = block312 313 # generate the root render function.302- self.writeline('def root(globals, environment=environment):', extra=1)314+ self.writeline('def root(globals, environment=environment'315+ ', standalone=False):', extra=1)316 self.indent()304- self.writeline('context = TemplateContext(globals, %r, blocks)' %305- self.filename)317+ self.writeline('context = TemplateContext(globals, %r, blocks'318+ ', standalone)' % self.filename)319 if have_extends:320 self.writeline('parent_root = None')321 self.outdent()322 1 unmodified line324 frame = Frame()325 frame.inspect(node.body)326 frame.toplevel = frame.rootlevel = True327 self.pull_locals(frame)328+ self.indent()329+ self.writeline('yield context')330+ self.outdent()315- self.blockvisit(node.body, frame, True)331+ self.blockvisit(node.body, frame)332 333 # make sure that the parent root is called.334 if have_extends:335 if not self.has_known_extends:336 self.indent()337 self.writeline('if parent_root is not None:')338 self.indent()323- self.writeline('for event in parent_root(context):')339+ self.writeline('stream = parent_root(context)')340+ self.writeline('stream.next()')341+ self.writeline('for event in stream:')342 self.indent()343 self.writeline('yield event')344 self.outdent(1 + self.has_known_extends)345 66 unmodified lines412 413 # and now we have one more414 self.extends_so_far += 1415 416+ def visit_Include(self, node, frame):417+ """Handles includes."""418+ # simpled include is include into a variable. This kind of419+ # include works the same on every level, so we handle it first.420+ if node.target is not None:421+ self.writeline('l_%s = ' % node.target, node)422+ if frame.toplevel:423+ self.write('context[%r] = ' % node.target)424+ self.write('IncludedTemplate(environment, context, ')425+ self.visit(node.template, frame)426+ self.write(')')427+ return428+429+ self.writeline('included_stream = environment.get_template(', node)430+ self.visit(node.template, frame)431+ self.write(').root_render_func(context, standalone=True)')432+ self.writeline('included_context = included_stream.next()')433+ self.writeline('for event in included_stream:')434+ self.indent()435+ self.writeline('yield event')436+ self.outdent()437+438+ # if we have a toplevel include the exported variables are copied439+ # into the current context without exporting them. context.udpate440+ # does *not* mark the variables as exported441+ if frame.toplevel:442+ self.writeline('context.update(included_context.get_exported())')443+444 def visit_For(self, node, frame):445 loop_frame = frame.inner()446 loop_frame.inspect(node.iter_child_nodes())447 extended_loop = bool(node.else_) or \104 unmodified lines552 553 self.newline(node)554 if self.environment.finalize is unicode:555 finalizer = 'unicode'556+ have_finalizer = False557 else:558 finalizer = 'context.finalize'559+ have_finalizer = False560 561 # if we are in the toplevel scope and there was already an extends562 # statement we have to add a check that disables our yield(s) here563 # so that they don't appear in the output.42 unmodified lines606 idx = -1607 for idx, argument in enumerate(arguments):608 if idx:609 self.write(', ')562- if finalizer != 'unicode':610+ if have_finalizer:611 self.write('(')612 self.visit(argument, frame)565- if finalizer != 'unicode':613+ if have_finalizer:614 self.write(')')615 self.write(idx == 0 and ',)' or ')')616 617 if outdent_later:135 unmodified lines753 self.visit(node.step, frame)754 755 def visit_Filter(self, node, frame):756 self.write('f_%s(' % node.name)757+ func = self.environment.filters.get(node.name)758+ if getattr(func, 'contextfilter', False):759+ self.write('context, ')760 self.visit(node.node, frame)761 self.signature(node, frame)762 self.write(')')763 764 def visit_Test(self, node, frame):714- self.write('environment.tests[%r](')765+ self.write('t_%s(' % node.name)766+ func = self.environment.tests.get(node.name)767+ if getattr(func, 'contexttest', False):768+ self.write('context, ')769 self.visit(node.node, frame)770 self.signature(node, frame)771 self.write(')')772 10 unmodified linesmodified:jinja2/environment.py+4 added-1 removed
143 unmodified lines144 def render(self, *args, **kwargs):145 return u''.join(self.stream(*args, **kwargs))146 147 def stream(self, *args, **kwargs):148- return self.root_render_func(dict(*args, **kwargs))148+ gen = self.root_render_func(dict(*args, **kwargs))149+ # skip the first item which is a reference to the stream150+ gen.next()151+ return genmodified:jinja2/parser.py+9 added-4 removed
159 unmodified lines160 node = nodes.Include(lineno=self.stream.expect('include').lineno)161 expr = self.parse_expression()162 if self.stream.current.type is 'assign':163 self.stream.next()164- if not expr.can_assign():164+ node.target = self.stream.expect('name')165+ # make sure that assignments to that name are allowed166+ if not nodes.Name(node.target, 'store').can_assign():167 raise TemplateSyntaxError('can\'t assign imported template '166- 'to this expression.', expr.lineno,168+ 'to %r' % node.target, expr.lineno,169 self.filename)168- expr.set_ctx('store')169- node.target = expr170 node.template = self.parse_expression()171 else:172 node.target = None173 node.template = expr11 unmodified lines185 186 def parse_macro(self):187 node = nodes.Macro(lineno=self.stream.expect('macro').lineno)188 node.name = self.stream.expect('name').value189+ # make sure that assignments to that name are allowed190+ if not nodes.Name(node.name, 'store').can_assign():191+ raise TemplateSyntaxError('can\'t assign macro to %r' %192+ node.target, node.lineno,193+ self.filename)194 self.stream.expect('lparen')195 node.args = args = []196 node.defaults = defaults = []197 while self.stream.current.type is not 'rparen':463 unmodified linesmodified:jinja2/runtime.py+35 added-6 removed
12 unmodified lines13 except ImportError:14 defaultdict = None15 16 17-__all__ = ['subscribe', 'LoopContext', 'StaticLoopContext',18- 'TemplateContext', 'Macro', 'Undefined']17+__all__ = ['subscribe', 'LoopContext', 'StaticLoopContext', 'TemplateContext',18+ 'Macro', 'IncludedTemplate', 'Undefined']19 20 21 def subscribe(obj, argument):22 """Get an item or attribute of an object."""21 unmodified lines44 update and other methods will not work as they seem (they don't update45 the exported variables for example).46 """47 48- def __init__(self, globals, filename, blocks):48+ def __init__(self, globals, filename, blocks, standalone):49 dict.__init__(self, globals)50 self.exported = set()51 self.filename = filename52 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())53- if isinstance(globals, TemplateContext):54- for name, parent_blocks in globals.blocks.iteritems():55- self.blocks.setdefault(name, []).extend(parent_blocks)53 54+ # if the template is in standalone mode we don't copy the blocks over.55+ # this is used for includes for example but otherwise, if the globals56+ # are a template context, this template is participating in a template57+ # inheritance chain and we have to copy the blocks over.58+ if not standalone and isinstance(globals, TemplateContext):59+ for name, parent_blocks in globals.blocks.iteritems():60+ self.blocks.setdefault(name, []).extend(parent_blocks)61+62 def __setitem__(self, key, value):63 """If we set items to the dict we track the variables set so64 that includes can access the exported variables."""65 dict.__setitem__(self, key, value)17 unmodified lines83 else:84 def __missing__(self, key):85 return Undefined(key)86 87+ def __repr__(self):88+ return '<%s %s of %r>' % (89+ self.__class__.__name__,90+ dict.__repr__(self),91+ self.filename92+ )93 94+95+class IncludedTemplate(object):96+ """Represents an included template."""97+98+ def __init__(self, environment, context, template):99+ root = environment.get_template(template).root_render_func100+ gen = root(context, standalone=True)101+ self._context = gen.next().get_exported()102+ self._rendered_body = u''.join(gen)103+104+ def __getitem__(self, name):105+ return self._context[name]106+107+ def __unicode__(self):108+ return self._context109+110+111 class LoopContextBase(object):112 """Helper for extended iteration."""113 114 def __init__(self, iterable, parent=None):10 unmodified lines125 length = property(lambda x: len(x))126 127 128 class LoopContext(LoopContextBase):129+ """A loop context for dynamic iteration."""130 131 def __init__(self, iterable, parent=None, enforce_length=False):132 self._iterable = iterable133 self._length = None114 unmodified linesmodified:test.py+5 added
2 unmodified lines3 4 env = Environment(loader=DictLoader({5 'child.html': u'''\6 {% extends master_layout or 'master.html' %}7+{% include 'helpers.html' %}8 {% macro get_the_answer() %}42{% endmacro %}9 {% block body %}10 {{ get_the_answer() }}11+ {{ conspirate() }}12 {% endblock %}13 ''',14 'master.html': u'''\15 <!doctype html>16 <title>Foo</title>17 {% block body %}{% endblock %}18+''',19+'helpers.html': u'''\20+{% macro conspirate() %}23{% endmacro %}21 '''22 }))23 24 2 unmodified lines