Skip to content
Myr

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

5 files+118 added−22 removed

modified:jinja2/compiler.py+65 added-11 removed
77 unmodified lines
7879 # names that are declared by parameters80 self.declared_parameter = set()8182 # filters that are referenced82 # filters/tests that are referenced83 self.filters = set()84 self.tests = set()8586 def add_special(self, name):87 """Register a special name like `loop`."""88 self.undeclared.discard(name)
77 unmodified lines
166 self.identifiers.undeclared.add(node.name)167168 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)171172 def visit_Test(self, node):173 self.generic_visit(node)174 self.identifiers.tests.add(node.name)175176 def visit_Macro(self, node):177 """Macros set local."""178 self.identifiers.declared_locally.add(node.name)179180 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)185186 def visit_Assign(self, node):187 """Visit assignments in the correct order."""188 self.visit(node.node)189 self.visit(node.target)
95 unmodified lines
285 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()293294 # -- Visitors
15 unmodified lines
310 self.filename)311 self.blocks[block.name] = block312313 # 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 line
324 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)332333 # 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 lines
412413 # and now we have one more414 self.extends_so_far += 1415416 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 return428429 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()437438 # 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())')443444 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 lines
552553 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 = False560561 # 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 lines
606 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 ')')616617 if outdent_later:
135 unmodified lines
753 self.visit(node.step, frame)754755 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(')')763764 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 lines
modified:jinja2/environment.py+4 added-1 removed
143 unmodified lines
144 def render(self, *args, **kwargs):145 return u''.join(self.stream(*args, **kwargs))146147 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 gen
modified:jinja2/parser.py+9 added-4 removed
159 unmodified lines
160 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 = expr
11 unmodified lines
185186 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 lines
modified:jinja2/runtime.py+35 added-6 removed
12 unmodified lines
13except ImportError:14 defaultdict = None151617__all__ = ['subscribe', 'LoopContext', 'StaticLoopContext',18 'TemplateContext', 'Macro', 'Undefined']17__all__ = ['subscribe', 'LoopContext', 'StaticLoopContext', 'TemplateContext',18 'Macro', 'IncludedTemplate', 'Undefined']192021def subscribe(obj, argument):22 """Get an item or attribute of an object."""
21 unmodified lines
44 update and other methods will not work as they seem (they don't update45 the exported variables for example).46 """4748 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)5354 # 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)6162 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 lines
83 else:84 def __missing__(self, key):85 return Undefined(key)8687 def __repr__(self):88 return '<%s %s of %r>' % (89 self.__class__.__name__,90 dict.__repr__(self),91 self.filename92 )939495class IncludedTemplate(object):96 """Represents an included template."""9798 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)103104 def __getitem__(self, name):105 return self._context[name]106107 def __unicode__(self):108 return self._context109110111class LoopContextBase(object):112 """Helper for extended iteration."""113114 def __init__(self, iterable, parent=None):
10 unmodified lines
125 length = property(lambda x: len(x))126127128class LoopContext(LoopContextBase):129 """A loop context for dynamic iteration."""130131 def __init__(self, iterable, parent=None, enforce_length=False):132 self._iterable = iterable133 self._length = None
114 unmodified lines
modified:test.py+5 added
2 unmodified lines
34env = 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}))2324
2 unmodified lines