[svn] implemented `{{ super() }}` for blocks. This checkin makes jinja much slower. I'll improve that as soon as possible
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 fee9fa1 · Browse files · 5 files·+114 added−14 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+114 added−14 removed
- tests:+12 added−0 removed
- other:+102 added−14 removed
Provenance
- Commit
a690146- Tree
73bd238- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
fee9fa1
5 files changed+114 added−14 removed
modified:jinja/translators/python.py+60 added-14 removed
166 unmodified lines167 Indent the current text.168 """169 return (' ' * (self.indention * 4)) + text170 171- def nodeinfo(self, node):171+ def nodeinfo(self, node, force=False):172 """173 Return a comment that helds the node informations or None174 if there is no need to add a debug comment.175 """2 unmodified lines178 rv = '# DEBUG(filename=%s, lineno=%s)' % (179 node.filename,180 node.lineno181 )182- if rv != self.last_debug_comment:182+ if force or rv != self.last_debug_comment:183 self.last_debug_comment = rv184 return rv185 186 def filter(self, s, filter_nodes):72 unmodified lines259 # root template.260 requirements_todo = []261 parent = None262 overwrites = {}263+ blocks = {}264 265 while node.extends is not None:266 # handle all requirements but not those from the267 # root template. The root template renders everything so3 unmodified lines271 272 # load the template we inherit from and add not known blocks273 parent = self.environment.loader.parse(node.extends.template,274 node.filename)274- # look up all block nodes and let them override each other275+ # look up all block nodes in the current template and276+ # add them to the override dict277 for n in get_nodes(nodes.Block, node):278 overwrites[n.name] = n279+ # handle direct overrides280 for n in get_nodes(nodes.Block, parent):281+ # an overwritten block for the parent template. handle that282+ # override in the template and register it in the deferred283+ # block dict.284 if n.name in overwrites:285+ blocks.setdefault(n.name, []).append(n.clone())286 n.replace(overwrites[n.name])287 # make the parent node the new node288 node = parent289 3 unmodified lines293 for n in req:294 if n.__class__ in (nodes.Set, nodes.Macro, nodes.Include):295 requirements.append(n)296 297+ # aliases boilerplate298+ aliases = ['%s = environment.%s' % (item, item) for item in299+ ['get_attribute', 'perform_test', 'apply_filters',300+ 'call_function', 'call_function_simple', 'finish_var']]301+302 # bootstrapping code303 lines = [304 'from __future__ import division\n'293- 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n'305+ 'from jinja.datastructure import Undefined, LoopContext, '306+ 'CycleContext, BlockContext\n'307 'from jinja.utils import buffereater\n'308+ '%s\n'309 '__name__ = %r\n\n'310 'def generate(context):\n'311 ' assert environment is context.environment\n'298- ' get_attribute = environment.get_attribute\n'299- ' perform_test = environment.perform_test\n'300- ' apply_filters = environment.apply_filters\n'301- ' call_function = environment.call_function\n'302- ' call_function_simple = environment.call_function_simple\n'303- ' finish_var = environment.finish_var\n'312 ' ctx_push = context.push\n'305- ' ctx_pop = context.pop\n' % node.filename313+ ' ctx_pop = context.pop' % (314+ '\n'.join(aliases),315+ node.filename316+ )317 ]318 319 # we have requirements? add them here.320 body_lines = []12 unmodified lines333 ' if p is None:\n'334 ' return translator.gettext(s) % (r or {})\n'335 ' return translator.ngettext(s, p, r[n]) % (r or {})'336 )337+338+ # add body lines and "generator hook"339 lines.extend(body_lines)340 lines.append(' if False:\n yield None')341 342+ # add the missing blocks343+ if blocks:344+ block_items = blocks.items()345+ block_items.sort()346+ dict_lines = []347+ for name, items in block_items:348+ tmp = []349+ for idx, item in enumerate(items):350+ # ensure that the indention is correct351+ self.indention = 1352+ func_name = 'block_%s_%s' % (name, idx)353+ lines.extend([354+ '\ndef %s(context):' % func_name,355+ ' ctx_push = context.push',356+ ' ctx_pop = context.pop',357+ ' if False:',358+ ' yield None'359+ ])360+ nodeinfo = self.nodeinfo(item, True)361+ if nodeinfo:362+ lines.append(self.indent(nodeinfo))363+ lines.append(self.handle_block(item, idx + 1))364+ tmp.append('buffereater(%s)' % func_name)365+ dict_lines.append(' %r: %s' % (366+ str(name),367+ _to_tuple(tmp)368+ ))369+ lines.append('\nblocks = {\n%s\n}' % ',\n'.join(dict_lines))370+371 return '\n'.join(lines)372 373 def handle_template_text(self, node):374 """12 unmodified lines387 buf = [self.handle_node(n) for n in node]388 if buf:389 nodeinfo = self.nodeinfo(node)390 if nodeinfo:349- buf = [self.indent(nodeinfo)] + buf391+ buf.insert(0, self.indent(nodeinfo))392 return '\n'.join(buf)393 394 def handle_for_loop(self, node):395 """204 unmodified lines600 self.indention -= 2601 write('yield %s' % self.filter('u\'\'.join(filtered())', node.filters))602 return '\n'.join(buf)603 562- def handle_block(self, node):604+ def handle_block(self, node, level=0):605 """606 Handle blocks in the sourcecode. We only use them to607 call the current block implementation that is stored somewhere608 else.4 unmodified lines613 614 buf = []615 write = lambda x: buf.append(self.indent(x))616 575- write('ctx_push()')617+ write('ctx_push({\'super\': BlockContext(%r, blocks[%r], %r, context)})' % (618+ str(node.name),619+ str(node.name),620+ level621+ ))622 nodeinfo = self.nodeinfo(node.body)623 if nodeinfo:624 write(nodeinfo)625 buf.append(self.handle_node(node.body))307 unmodified linesmodified:jinja/datastructure.py+20 added
314 unmodified lines315 self.lineno = (self.lineno + 1) % len(seq)316 return seq[self.lineno]317 318 319+class BlockContext(object):320+ """321+ Helper class for ``{{ super() }}``.322+ """323+ jinja_allowed_attributes = ['name']324+325+ def __init__(self, name, stack, level, context):326+ self.name = name327+ self.context = context328+ if len(stack) > level:329+ self.block = stack[level]330+ else:331+ self.block = None332+333+ def __call__(self):334+ if self.block is None:335+ raise TemplateRuntimeError('no super block for %r' % self.name)336+ return self.block(self.context)337+338+339 class TokenStream(object):340 """341 A token stream works like a normal generator just that342 it supports pushing tokens back to the stream.60 unmodified linesmodified:jinja/nodes.py+8 added
270 unmodified lines271 """272 assert node.__class__ is Block273 self.__dict__.update(node.__dict__)274 275+ def clone(self):276+ """277+ Create an independent clone of this node.278+ """279+ rv = Block(None, None, None)280+ rv.__dict__.update(self.__dict__)281+ return rv282+283 def get_items(self):284 return [self.name, self.body]285 286 def __repr__(self):64 unmodified linesadded:tests/runtime/super.py+12 added
1+# test file for block super support2+import jdebug3+from jinja import Environment, DictLoader4+5+env = Environment(loader=DictLoader({6+ 'a': '{% block intro %}INTRO{% endblock %}|BEFORE|{% block data %}INNER{% endblock %}|AFTER',7+ 'b': '{% extends "a" %}{% block data %}({{ super() }}){% endblock %}',8+ 'c': '{% extends "b" %}{% block intro %}--{{ super() }}--{% endblock %}\n{% block data %}[{{ super() }}]{% endblock %}'9+}))10+11+tmpl = env.get_template('c')12+print tmpl.render()modified:jdebug.py+14 added
6 unmodified lines7 8 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+import os12+import sys13 from jinja import Environment14 from jinja.parser import Parser15 from jinja.lexer import Lexer16 from jinja.translators.python import PythonTranslator3 unmodified lines20 21 e = Environment()22 t = e.from_string23 24+25+if os.environ.get('JDEBUG_SOURCEPRINT'):26+ original_translate = PythonTranslator.translate27+28+ def debug_translate(self):29+ rv = original_translate(self)30+ sys.stderr.write('## GENERATED SOURCE:\n%s\n' % rv)31+ return rv32+33+ PythonTranslator.translate = debug_translate34+35+36 def p(x):37 print PythonTranslator(e, Parser(e, x).parse()).translate()38 39 def l(x):2 unmodified lines