[svn] fixes jinja inheritance code
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 34a18bf · Browse files · 7 files·+65 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+65 added−34 removed
- tests:+12 added−1 removed
- other:+53 added−33 removed
Provenance
- Commit
56ae6e0- Tree
c3af043- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
34a18bf
7 files changed+65 added−34 removed
modified:jinja/translators/python.py+17 added-15 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from compiler import ast12 from jinja import nodes13+from jinja.nodes import get_nodes14 from jinja.parser import Parser15 from jinja.exceptions import TemplateSyntaxError16 from jinja.translators import Translator17 194 unmodified lines212 ensures that we get the bootstrapping code. It also knows about213 inheritance information. It only occours as outer node, never in214 the tree itself.215 """216+ self.indention = 1217+218 # if there is a parent template we parse the parent template and219 # update the blocks there. Once this is done we drop the current220 # template in favor of the new one. Do that until we found the221 # root template.222 requirements_todo = []220- blocks = node.blocks.copy()223 parent = None224 225 while node.extends is not None:226 # handle all requirements but not those from the5 unmodified lines232 # load the template we inherit from and add not known blocks233 # to the block registry, make this template the new root.234 parent = self.environment.loader.parse(node.extends.template,235 node.filename)234- for name, block in parent.blocks.iteritems():235- if name not in blocks:236- blocks[name] = block236 237+ overwrites = {}238+ for n in get_nodes(nodes.Block, node):239+ overwrites[n.name] = n240+ for n in get_nodes(nodes.Block, parent):241+ if n.name in overwrites:242+ n.replace(overwrites[n.name])243+244 node = parent245 240- # if there is a parent template, do the inheritance handling now241- if parent is not None:242- for name, block in blocks.iteritems():243- if name in node.blocks:244- node.blocks[name].replace(block)245-246 # look up requirements247 requirements = []248 for req in requirements_todo:249 for n in req:16 unmodified lines266 ' finish_var = environment.finish_var\n'267 ' ctx_push = context.push\n'268 ' ctx_pop = context.pop\n'269 ]270- self.indention = 1270 271 # we have requirements? add them here.272 if requirements:273 lines.append(self.indent('# REQUIREMENTS'))214 unmodified lines488 else.489 """490 rv = self.handle_node(node.body)491 if not rv:493- return self.indent('# EMPTY BLOCK FROM %r, LINE %s' % (492+ return self.indent('# EMPTY BLOCK "%s" FROM %r, LINE %s' % (493+ node.name,494 node.filename or '?',495 node.lineno496 ))497 498 buf = []499 write = lambda x: buf.append(self.indent(x))500 501- write('# BLOCK FROM %r, LINE %s' % (501+ write('# BLOCK "%s" FROM %r, LINE %s' % (502+ node.name,503 node.filename or '?',504 node.lineno505 ))506 write('ctx_push()')119 unmodified lines626 return '%s[%s]' % (627 self.handle_node(node.expr),628 self.handle_node(node.subs[0])629 )629- return 'get_attribute(%s, %s)' % (630+ return 'get_attribute(%s, (%s,))' % (631 self.handle_node(node.expr),632 self.handle_node(node.subs[0])633 )634 5 unmodified lines640 641 # chain getattrs for speed reasons642 path = [repr(node.attrname)]643 while node.expr.__class__ is ast.Getattr:643- path.append(repr(node.attrname))644 node = node.expr645+ path.append(repr(node.attrname))646+ path.reverse()647 648 return 'get_attribute(%s, %s)' % (649 self.handle_node(node.expr),650 _to_tuple(path)182 unmodified linesmodified:jinja/environment.py+2 added-2 removed
140 unmodified lines141 for name in attributes:142 try:143 node = node[name]144 except (TypeError, KeyError, IndexError):145- if not hasattr(obj, name):145+ if not hasattr(node, name):146 return Undefined147 r = getattr(obj, 'jinja_allowed_attributes', None)148 if r is not None and name not in r:149 raise SecurityException('unsafe attributed %r accessed' % name)150- node = getattr(obj, name)150+ node = getattr(node, name)151 return node152 153 def call_function(self, f, args, kwargs, dyn_args, dyn_kwargs):154 """36 unmodified linesmodified:jinja/nodes.py+23 added-9 removed
24 unmodified lines25 node.lineno = offset26 todo.extend(node.getChildNodes())27 28 29+def get_nodes(nodetype, tree):30+ """31+ Get all nodes from nodetype in the tree.32+ """33+ todo = [tree]34+ while todo:35+ node = todo.pop()36+ if node.__class__ is nodetype:37+ yield node38+ todo.extend(node.getChildNodes())39+40+41 class Node(ast.Node):42 """43 jinja node.44 """35 unmodified lines80 81 getChildren = getChildNodes = lambda s: list(s) + s.get_items()82 83 def __repr__(self):72- return '%s(%s)' % (73- self.__class__.__name__,74- list.__repr__(self)75- )84+ return 'NodeList(%s)' % list.__repr__(self)85 86 87 class Template(NodeList):88 """89 Node that represents a template.90 """91 83- def __init__(self, filename, body, blocks, extends):92+ def __init__(self, filename, body, extends):93 if body.__class__ is not NodeList:94 body = (body,)95 NodeList.__init__(self, 0, body)87- self.blocks = blocks96 self.extends = extends97 set_filename(filename, self)98 99 def get_items(self):92- result = self.blocks.values()100 if self.extends is not None:94- result.append(self.extends)95- return result101+ return [self.extends]102+ return []103 104+ def __repr__(self):105+ return 'Template(%r, %r, %r)' % (106+ self.filename,107+ self.extends,108+ NodeList.__repr__(self)109+ )110 111+112 class ForLoop(Node):113 """114 A node that represents a for loop115 """230 unmodified linesmodified:jinja/parser.py+11 added-7 removed
12 unmodified lines13 from compiler.misc import set_filename14 from jinja import nodes15 from jinja.datastructure import TokenStream16 from jinja.exceptions import TemplateSyntaxError17+try:18+ set19+except NameError:20+ from sets import Set as set21 22 23 # callback functions for the subparse method24 end_of_block = lambda p, t, d: t == 'block_end'42 unmodified lines67 self.filename = filename68 self.tokenstream = environment.lexer.tokenize(source)69 70 self.extends = None67- self.blocks = {}71+ self.blocks = set()72 73 self.directives = {74 'for': self.handle_for_directive,75 'if': self.handle_if_directive,148 unmodified lines224 if block_name[1] != 'name':225 raise TemplateSyntaxError('expected \'name\', got %r' %226 block_name[1], lineno)227 if tokens:224- print tokens228 raise TemplateSyntaxError('block got too many arguments, '229 'requires one.', lineno)230 231+ # check if this block does not exist by now.232 if block_name[2] in self.blocks:233 raise TemplateSyntaxError('block %r defined twice' %230- block_name[2], lineno)234+ block_name[2], lineno)235+ self.blocks.add(block_name[2])236 237+ # now parse the body and attach it to the block238 body = self.subparse(end_of_block_tag, True)239 self.close_remaining_block()234- rv = nodes.Block(lineno, block_name[2], body)235- self.blocks[block_name[2]] = rv236- return rv240+ return nodes.Block(lineno, block_name[2], body)241 242 def handle_extends_directive(self, lineno, gen):243 """244 Handle the extends directive used for inheritance.153 unmodified lines398 """399 Parse the template and return a Template node.400 """401 body = self.subparse(None)398- return nodes.Template(self.filename, body, self.blocks, self.extends)402+ return nodes.Template(self.filename, body, self.extends)403 404 def subparse(self, test, drop_needle=False):405 """406 Helper function used to parse the sourcecode until the test91 unmodified linesmodified:tests/templates/a.html+3 added
3 unmodified lines4567891011123 unmodified lines{% block block4 %} nested block from template a.html {% block block5 %} contents of the nested block from a.html {% block block6 %} double nested block. {% endblock %} {% endblock %}{% endblock %}modified:tests/templates/b.html+6 added-1 removed
123345678{% extends 'a.html' %}{% block block1 %}from template b.html{% endblock %}{% block block5 %}contents of nested block from b.html{% endblock %}{% block block5 %} contents of nested block from b.html {% block block7 %} new nested block introduced in b.html {% endblock %}{% endblock %}modified:tests/templates/c.html+3 added
123456{% extends 'b.html' %}{% block block2 %}from template c.html{% endblock %}{% block block3 %}from template c.html{% endblock %}{% block block7 %} nested block from b.html, overridden in c.html{% endblock %}