Skip to content
Myr

[svn] fixed supering in jinja, documented it, added lipsum()

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 5adf94f · Browse files · 8 files+242 added−136 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+242 added−136 removed

  • tests:+6 added−2 removed
  • other:+236 added−134 removed

8 files+242 added−136 removed

modified:docs/src/designerdoc.txt+41 added
134 unmodified lines
135`debug`136137 Function that outputs the contents of the context.138139`lipsum`140141 Generate some paragraphs of random text:142143 .. sourcecode:: jinja144145 {{ lipsum(5) }}146 five html paragraphs147148 {{ lipsum(2, False) }}149 two ascii only paragraphs150151 Per default a paragraph is between 20 and 100 words long. You can152 override this default with the third and fourth parameter:153154 .. sourcecode:: jinja155156 {{ lipsum(10, True, 50, 200) }}157 generate 10 HTML paragraphs between 50 and 200 words.158159 *new in Jinja 1.1*160161Loops162=====163164To iterate over a sequence, you can use the `for` loop. It basically looks like a
331 unmodified lines
496 also defines the content that fills the hole in the *parent*. If there were497 two similarly-named ``{% block %}`` tags in a template, that template's498 parent wouldn't know which one of the blocks' content to use.499500Super Blocks501============502503Starting with `Jinja 1.1` it's possible to render the contents of the parent504block. By calling it you get the results of the parent block back. If you want505to get the data of the parent you can give it an offset:506507.. sourcecode:: jinja508509 {{ super() }}510 return the parent data511512 {{ super(1) }}513 the same as above514515 {{ super(2) }}516 return the data of the second parent block517518519Template Inclusion520==================521522You can load another template at a given position using ``{% include %}``.
271 unmodified lines
modified:jinja/translators/python.py+85 added-85 removed
6 unmodified lines
78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12import sys13from compiler import ast14from jinja import nodes15from jinja.nodes import get_nodes16from jinja.parser import Parser17from jinja.exceptions import TemplateSyntaxError18from jinja.translators import Translator18from jinja.utils import translate_exception, capture_generator19from jinja.utils import translate_exception, capture_generator, \20 RUNTIME_EXCEPTION_OFFSET212223#: regular expression for the debug symbols24_debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '25 r'lineno=(?P<lineno>\d+)\)$')262728def _to_tuple(args):29 """30 Return a tuple repr without nested repr.31 """
7 unmodified lines
39 """40 Represents a finished template.41 """4236 def __init__(self, environment, code, translated_source=None):43 def __init__(self, environment, code):44 self.environment = environment45 self.code = code39 self.translated_source = translated_source46 self.generate_func = None47 #: holds debug information48 self._debug_info = None49 #: unused in loader environments but used when a template50 #: is loaded from a string in order to be able to debug those too51 self._source = None5253 def dump(self, stream=None):54 """Dump the template into python bytecode."""55 if stream is not None:56 from marshal import dump46 dump((self.code, self.translated_source), stream)57 dump(self.code, stream)58 else:59 from marshal import dumps49 return dumps((self.code, self.translated_source))60 return dumps(self.code)6162 def load(environment, data):63 """Load the template from python bytecode."""64 if isinstance(data, basestring):65 from marshal import loads55 code, src = loads(data)66 code = loads(data)67 else:68 from marshal import load58 code, src = load(data)59 return Template(environment, code, src)69 code = load(data)70 return Template(environment, code)71 load = staticmethod(load)7273 def render(self, *args, **kwargs):74 """Render a template."""75 # if there is no generation function we execute the code76 # in a new namespace and save the generation function and77 # debug information.78 if self.generate_func is None:79 ns = {'environment': self.environment}80 exec self.code in ns81 self.generate_func = ns['generate']82 self._debug_info = ns['debug_info']83 ctx = self.environment.context_class(self.environment, *args, **kwargs)84 try:85 return capture_generator(self.generate_func(ctx))86 except:87 # debugging system:88 # on any exception we first get the current exception information89 # and skip the internal frames (currently either one (python2.5)90 # or two (python2.4 and lower)). After that we call a function91 # that creates a new traceback that is easier to debug.92 exc_type, exc_value, traceback = sys.exc_info()73 # translate the exception, We skip two frames. One74 # frame that is the "capture_generator" frame, and another75 # one which is the frame of this function93 for _ in xrange(RUNTIME_EXCEPTION_OFFSET):94 traceback = traceback.tb_next95 traceback = translate_exception(self, exc_type, exc_value,77 traceback.tb_next.tb_next, ctx)96 traceback, ctx)97 raise exc_type, exc_value, traceback9899100class PythonTranslator(Translator):
73 unmodified lines
174 translator = PythonTranslator(environment, node)175 filename = node.filename or '<template>'176 source = translator.translate()177 return Template(environment,159 compile(source, filename, 'exec'),160 source)178 compile(source, filename, 'exec'))179 process = staticmethod(process)180181 # -- private helper methods182
7 unmodified lines
190 """191 Return a comment that helds the node informations or None192 if there is no need to add a debug comment.193 """176 if node.filename is None:177 return178 rv = '# DEBUG(filename=%s, lineno=%s)' % (179 node.filename,194 return '# DEBUG(filename=%s, lineno=%s)' % (195 node.filename or '',196 node.lineno197 )182 if force or rv != self.last_debug_comment:183 self.last_debug_comment = rv184 return rv198199 def filter(self, s, filter_nodes):200 """201 Apply a filter on an object that already is a python expression.
46 unmodified lines
248249 def reset(self):250 self.indention = 0251 self.last_cycle_id = 0239 self.last_debug_comment = None252253 def translate(self):254 self.reset()255 return self.handle_node(self.node)
58 unmodified lines
314 # bootstrapping code315 lines = [316 'from __future__ import division\n'317 'from jinja.datastructure import Undefined, LoopContext, '306 'CycleContext, BlockContext\n'318 'CycleContext, SuperBlock\n'319 'from jinja.utils import buffereater\n'320 '%s\n'321 '__name__ = %r\n\n'322 'def generate(context):\n'
45 unmodified lines
368 ' ctx_pop = context.pop',369 ' if False:',370 ' yield None'371 ])360 nodeinfo = self.nodeinfo(item, True)361 if nodeinfo:362 lines.append(self.indent(nodeinfo))372 lines.append(self.indent(self.nodeinfo(item, True)))373 lines.append(self.handle_block(item, idx + 1))374 tmp.append('buffereater(%s)' % func_name)375 dict_lines.append(' %r: %s' % (376 str(name),377 _to_tuple(tmp)378 ))379 lines.append('\nblocks = {\n%s\n}' % ',\n'.join(dict_lines))380371 return '\n'.join(lines)381 # now get the real source lines and map the debugging symbols382 debug_mapping = []383 last = None384 offset = -1385 sourcelines = ('\n'.join(lines)).splitlines()386 result = []387388 for idx, line in enumerate(sourcelines):389 m = _debug_re.search(line)390 if m is not None:391 d = m.groupdict()392 this = (d['filename'] or None, int(d['lineno']))393 # if there is no filename in this debug symbol394 # if it's the same as the line before we ignore it395 if this[0] and this != last:396 debug_mapping.append((idx - offset,) + this)397 last = this398 # for each debug symbol the line number and so the offset399 # changes by one.400 offset += 1401 else:402 result.append(line)403404 result.append('\ndebug_info = %r' % debug_mapping)405 return '\n'.join(result)406407 def handle_template_text(self, node):408 """409 Handle data around nodes.410 """377 nodeinfo = self.nodeinfo(node) or ''378 if nodeinfo:379 nodeinfo = self.indent(nodeinfo) + '\n'380 return nodeinfo + self.indent('yield %r' % node.text)411 return self.indent(self.nodeinfo(node)) + '\n' +\412 self.indent('yield %r' % node.text)413414 def handle_node_list(self, node):415 """416 In some situations we might have a node list. It's just417 a collection of multiple statements.418 """387 buf = [self.handle_node(n) for n in node]388 if buf:389 nodeinfo = self.nodeinfo(node)390 if nodeinfo:391 buf.insert(0, self.indent(nodeinfo))392 return '\n'.join(buf)419 return '\n'.join([self.indent(self.nodeinfo(node))] +420 [self.handle_node(n) for n in node])421422 def handle_for_loop(self, node):423 """424 Handle a for loop. Pretty basic, just that we give the else425 clause a different behavior.426 """427 buf = []428 write = lambda x: buf.append(self.indent(x))401 nodeinfo = self.nodeinfo(node)402 if nodeinfo:403 write(nodeinfo)429 write(self.nodeinfo(node))430 write('ctx_push()')431432 # recursive loops433 if node.recursive:
12 unmodified lines
446 )447448 # handle real loop code449 self.indention += 1424 nodeinfo = self.nodeinfo(node.body)425 if nodeinfo:426 write(nodeinfo)450 write(self.nodeinfo(node.body))451 buf.append(self.handle_node(node.body) or self.indent('pass'))452 self.indention -= 1453454 # else part of loop455 if node.else_:456 write('if not context[\'loop\'].iterated:')457 self.indention += 1434 nodeinfo = self.nodeinfo(node.else_)435 if nodeinfo:436 write(nodeinfo)458 write(self.nodeinfo(node.else_))459 buf.append(self.handle_node(node.else_) or self.indent('pass'))460 self.indention -= 1461462 # call recursive for loop!
17 unmodified lines
480 Handle an if condition node.481 """482 buf = []483 write = lambda x: buf.append(self.indent(x))462 nodeinfo = self.nodeinfo(node)463 if nodeinfo:464 write(nodeinfo)484 write(self.nodeinfo(node))485 for idx, (test, body) in enumerate(node.tests):486 write('%sif %s:' % (487 idx and 'el' or '',488 self.handle_node(test)489 ))490 self.indention += 1471 nodeinfo = self.nodeinfo(body)472 if nodeinfo:473 write(nodeinfo)491 write(self.nodeinfo(body))492 buf.append(self.handle_node(body))493 self.indention -= 1494 if node.else_ is not None:495 write('else:')496 self.indention += 1479 nodeinfo = self.nodeinfo(node.else_)480 if nodeinfo:481 write(nodeinfo)497 write(self.nodeinfo(node.else_))498 buf.append(self.handle_node(node.else_))499 self.indention -= 1500 return '\n'.join(buf)501
7 unmodified lines
509 write = lambda x: buf.append(self.indent(x))510511 write('if not %r in context.current:' % name)512 self.indention += 1497 nodeinfo = self.nodeinfo(node)498 if nodeinfo:499 write(nodeinfo)513 write(self.nodeinfo(node))514 if node.seq.__class__ in (ast.Tuple, ast.List):515 write('context.current[%r] = CycleContext(%s)' % (516 name,517 _to_tuple([self.handle_node(n) for n in node.seq.nodes])
17 unmodified lines
535 def handle_print(self, node):536 """537 Handle a print statement.538 """525 nodeinfo = self.nodeinfo(node) or ''526 if nodeinfo:527 nodeinfo = self.indent(nodeinfo) + '\n'528 return nodeinfo + self.indent('yield finish_var(%s, context)' %529 self.handle_node(node.variable))539 return self.indent(self.nodeinfo(node)) + '\n' +\540 self.indent('yield finish_var(%s, context)' %541 self.handle_node(node.variable))542543 def handle_macro(self, node):544 """545 Handle macro declarations.
2 unmodified lines
548 write = lambda x: buf.append(self.indent(x))549550 write('def macro(*args):')551 self.indention += 1540 nodeinfo = self.nodeinfo(node)541 if nodeinfo:542 write(nodeinfo)552 write(self.nodeinfo(node))553554 if node.arguments:555 write('argcount = len(args)')556 tmp = []
7 unmodified lines
564 write('ctx_push({%s})' % ', '.join(tmp))565 else:566 write('ctx_push()')567558 nodeinfo = self.nodeinfo(node.body)559 if nodeinfo:560 write(nodeinfo)568 write(self.nodeinfo(node.body))569 buf.append(self.handle_node(node.body))570 write('ctx_pop()')571 write('if False:')572 self.indention += 1
6 unmodified lines
579 def handle_set(self, node):580 """581 Handle variable assignments.582 """575 nodeinfo = self.nodeinfo(node) or ''576 if nodeinfo:577 nodeinfo = self.indent(nodeinfo) + '\n'578 return nodeinfo + self.indent('context[%r] = %s' % (583 return self.indent(self.nodeinfo(node)) + '\n' + \584 self.indent('context[%r] = %s' % (585 node.name,586 self.handle_node(node.expr)587 ))588
5 unmodified lines
594 write = lambda x: buf.append(self.indent(x))595 write('def filtered():')596 self.indention += 1597 write('ctx_push()')592 nodeinfo = self.nodeinfo(node.body)593 if nodeinfo:594 write(nodeinfo)598 write(self.nodeinfo(node.body))599 buf.append(self.handle_node(node.body))600 write('ctx_pop()')601 write('if False:')602 self.indention += 1
14 unmodified lines
617618 buf = []619 write = lambda x: buf.append(self.indent(x))620621 write(self.nodeinfo(node))617 write('ctx_push({\'super\': BlockContext(%r, blocks[%r], %r, context)})' % (622 write('ctx_push({\'super\': SuperBlock(%r, blocks, %r, context)})' % (623 str(node.name),619 str(node.name),624 level625 ))622 nodeinfo = self.nodeinfo(node.body)623 if nodeinfo:624 write(nodeinfo)626 write(self.nodeinfo(node.body))627 buf.append(self.handle_node(node.body))628 write('ctx_pop()')629 return '\n'.join(buf)630
19 unmodified lines
650 ))651 replacements = '{%s}' % ', '.join(replacements)652 else:653 replacements = 'None'652 nodeinfo = self.nodeinfo(node) or ''653 if nodeinfo:654 nodeinfo = self.indent(nodeinfo) + '\n'655 return nodeinfo + self.indent('yield translate(%r, %r, %r, %s)' % (654 return self.indent(self.nodeinfo(node)) + '\n' +\655 self.indent('yield translate(%r, %r, %r, %s)' % (656 node.singular,657 node.plural,658 node.indicator,659 replacements
273 unmodified lines
modified:jinja/datastructure.py+24 added-14 removed
293 unmodified lines
294 Helper class used for cycling.295 """296297 def __init__(self, seq=None):298 self.lineno = -1298 self.pos = -1299 # bind the correct helper function based on the constructor signature300 if seq is not None:301 self.seq = seq302 self.length = len(seq)
2 unmodified lines
305 self.cycle = self.cycle_dynamic306307 def cycle_static(self):308 """Helper function for static cycling."""309 self.lineno = (self.lineno + 1) % self.length310 return self.seq[self.lineno]309 self.pos = (self.pos + 1) % self.length310 return self.seq[self.pos]311312 def cycle_dynamic(self, seq):313 """Helper function for dynamic cycling."""314 self.lineno = (self.lineno + 1) % len(seq)315 return seq[self.lineno]314 self.pos = pos = (self.pos + 1) % len(seq)315 return seq[pos]316317318class BlockContext(object):318class SuperBlock(object):319 """320 Helper class for ``{{ super() }}``.321 """322 jinja_allowed_attributes = ['name']323324 def __init__(self, name, stack, level, context):324 def __init__(self, name, blocks, level, context):325 self.name = name326 self.context = context327 if len(stack) > level:328 self.block = stack[level]327 if name in blocks:328 self.stack = blocks[name]329 self.level = level330 else:330 self.block = None331 self.stack is None332 if len(stack) > level:333 self.block = stack[level]334332 def __call__(self):333 if self.block is None:334 raise TemplateRuntimeError('no super block for %r' % self.name)335 return self.block(self.context)335 def __call__(self, offset=1):336 level = self.level + (offset - 1)337 if level < len(self.stack):338 return self.stack[level](self.context)339 raise TemplateRuntimeError('no super block for %r' % self.name)340341 def __repr__(self):342 return '<SuperBlock %r (%spossible)>' % (343 self.name,344 self.stack is None and 'im' or ''345 )346347348class TokenStream(object):349 """350 A token stream works like a normal generator just that351 it supports pushing tokens back to the stream.
60 unmodified lines
modified:jinja/defaults.py+3 added-2 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS13from jinja.utils import debug_context, safe_range13from jinja.utils import debug_context, safe_range, generate_lorem_ipsum141516DEFAULT_NAMESPACE = {17 'range': safe_range,18 'debug': debug_context18 'debug': debug_context,19 'lipsum': generate_lorem_ipsum20}
modified:jinja/environment.py+4 added-1 removed
85 unmodified lines
86 def from_string(self, source):87 """Load a template from a string."""88 from jinja.parser import Parser89 from jinja.translators.python import PythonTranslator90 return PythonTranslator.process(self, Parser(self, source).parse())90 rv = PythonTranslator.process(self, Parser(self, source).parse())91 # attach the source for debugging92 rv._source = source93 return rv9495 def get_template(self, filename):96 """Load a template from a filename. Only works97 if a proper loader is set."""
118 unmodified lines
modified:jinja/utils.py+77 added-30 removed
17 unmodified lines
18from types import MethodType, FunctionType19from compiler.ast import CallFunc, Name, Const20from jinja.nodes import Trans21from jinja.datastructure import Context, TemplateData22from jinja.exceptions import SecurityException22from jinja.exceptions import SecurityException, TemplateNotFound2324try:25 from collections import deque26except ImportError:
1 unmodified line
2829#: number of maximal range items30MAX_RANGE = 10000003132_debug_info_re = re.compile(r'^\s*\# DEBUG\(filename=(.*?), lineno=(.*?)\)$')3332_integer_re = re.compile('^(\d+)$')3334_word_split_re = re.compile(r'(\s+)')35
111 unmodified lines
147 return range(0, start, step)148 return range(start, stop, step)149150151def generate_lorem_ipsum(n=5, html=True, min=20, max=100):152 """153 Generate some lorem impsum for the template.154 """155 from jinja.constants import LOREM_IPSUM_WORDS156 from random import choice, random, randrange157 words = LOREM_IPSUM_WORDS.split()158 result = []159160 for _ in xrange(n):161 next_capitalized = True162 last_comma = last_fullstop = 0163 word = None164 last = None165 p = []166167 # each paragraph contains out of 20 to 100 words.168 for idx, _ in enumerate(xrange(randrange(min, max))):169 while True:170 word = choice(words)171 if word != last:172 last = word173 break174 if next_capitalized:175 word = word.capitalize()176 next_capitalized = False177 # add commas178 if idx - randrange(3, 8) > last_comma:179 last_comma = idx180 last_fullstop += 2181 word += ','182 # add end of sentences183 if idx - randrange(10, 20) > last_fullstop:184 last_comma = last_fullstop = idx185 word += '.'186 next_capitalized = True187 p.append(word)188189 # ensure that the paragraph ends with a dot.190 p = u' '.join(p)191 if p.endswith(','):192 p = p[:-1] + '.'193 elif not p.endswith('.'):194 p += '.'195 result.append(p)196197 if not html:198 return u'\n\n'.join(result)199 return u'\n'.join([u'<p>%s</p>' % escape(x) for x in result])200201202# python2.4 and lower has a bug regarding joining of broken generators203# because of the runtime debugging system we have to keep track of the204# number of frames to skip. that's what RUNTIME_EXCEPTION_OFFSET is for.205if sys.version_info < (2, 5):206 capture_generator = lambda gen: u''.join(tuple(gen))207 RUNTIME_EXCEPTION_OFFSET = 2208209# this should be faster and used in python2.5 and higher210else:211 capture_generator = u''.join212 RUNTIME_EXCEPTION_OFFSET = 1213214215def buffereater(f):216 """
4 unmodified lines
221 return TemplateData(capture_generator(f(*args, **kwargs)))222 return wrapped223224172def fake_template_exception(exception, filename, lineno, context_or_env):225def fake_template_exception(exception, filename, lineno, template,226 context_or_env):227 """228 Raise an exception "in a template". Return a traceback229 object. This is used for runtime debugging, not compile time.230 """
10 unmodified lines
241 code = compile(offset + 'raise __exception_to_raise__', filename, 'exec')242 globals = {243 '__name__': filename,244 '__file__': filename,191 '__loader__': TracebackLoader(env, filename),245 '__loader__': TracebackLoader(env, template, filename),246 '__exception_to_raise__': exception247 }248 try:249 exec code in globals, namespace
4 unmodified lines
254def translate_exception(template, exc_type, exc_value, traceback, context):255 """256 Translate an exception and return the new traceback.257 """204 sourcelines = template.translated_source.splitlines()205 startpos = traceback.tb_lineno - 1206 filename = None207 # looks like we loaded the template from string. we cannot208 # do anything here.209 if startpos > len(sourcelines):210 return traceback211212 while startpos > 0:213 m = _debug_info_re.search(sourcelines[startpos])214 if m is not None:215 filename, lineno = m.groups()216 if filename == 'None':217 filename = None218 if lineno != 'None':219 lineno = int(lineno)258 error_line = traceback.tb_lineno259 for code_line, tmpl_filename, tmpl_line in template._debug_info[::-1]:260 if code_line <= error_line:261 break221 startpos -= 1222223 # no traceback information found, reraise unchanged224 if not filename:262 else:263 # no debug symbol found. give up264 return traceback265227 return fake_template_exception(exc_value, filename,228 lineno, context)[2]266 return fake_template_exception(exc_value, tmpl_filename, tmpl_line,267 template, context)[2]268269270def raise_syntax_error(exception, env):271 """
2 unmodified lines
274 `translate_exception` this method raises the exception with275 the traceback.276 """277 exc_info = fake_template_exception(exception, exception.filename,239 exception.lineno, env)278 exception.lineno, None, env)279 raise exc_info[0], exc_info[1], exc_info[2]280281282def collect_translations(ast):
31 unmodified lines
314 """315 Fake importer that just returns the source of a template.316 """317279 def __init__(self, environment, filename):318 def __init__(self, environment, template, filename):319 self.loader = environment.loader320 self.template = template321 self.filename = filename322323 def get_source(self, impname):324 if self.loader is not None:325 try:284 return self.loader.get_source(self.filename)326 return self.loader.get_source(self.filename)327 except TemplateNotFound:328 pass329 if self.template is not None:330 return self.template._source or ''331 return ''332333334class CacheDict(object):335 """
124 unmodified lines
modified:tests/runtime/exception.py+6 added-2 removed
1import jdebug2import sys3from jinja import Environment, DictLoader4from jinja.exceptions import TemplateNotFound3from colubrid.debug import DebuggedApplication5from wsgiref.simple_server import make_server67e = Environment(loader=DictLoader({8 '/': u'''
59 unmodified lines
68 return ['NOT FOUND']69 start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])70 return [tmpl.render().encode('utf-8')]7172if __name__ == '__main__':73 from colubrid.debug import DebuggedApplication74 app = DebuggedApplication(test)71make_server("localhost", 7000, DebuggedApplication(test)).serve_forever()75 make_server("localhost", 7000, app).serve_forever()
modified:jdebug.py+2 added-2 removed
31 unmodified lines
3233 PythonTranslator.translate = debug_translate343536def p(x):37 print PythonTranslator(e, Parser(e, x).parse()).translate()36def p(x, f=None):37 print PythonTranslator(e, Parser(e, x, f).parse()).translate()3839def l(x):40 for item in e.lexer.tokenize(x):41 print '%5s %-20s %r' % item