[svn] again many changes in jinja. Performance improvements and much more
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk rename : tests/inheritance.py => tests/layout.py
authored by Armin Ronacher · committed by Armin Ronacher · parent a5f6234 · Browse files · 14 files·+439 added−141 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+439 added−141 removed
- tests:+30 added−7 removed
- other:+409 added−134 removed
Provenance
- Commit
34a18bf- Tree
485c57f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
a5f6234
14 files changed+439 added−141 removed
modified:jinja/translators/python.py+104 added-68 removed
33 unmodified lines34 self.environment = environment35 self.code = code36 self.generate_func = None37 38- def dump(self, filename):38+ def dump(self, stream=None):39 """Dump the template into python bytecode."""40+ if stream is not None:41+ from marshal import dump42+ dump(self.code, stream)43+ else:40- from marshal import dumps41- return dumps(self.code)44+ from marshal import dumps45+ return dumps(self.code)46 47 def load(environment, data):48 """Load the template from python bytecode."""49+ if isinstance(data, basestring):45- from marshal import loads46- code = loads(data)50+ from marshal import loads51+ code = loads(data)52+ else:53+ from marshal import load54+ code = load(data)55 return Template(environment, code)56 load = staticmethod(load)57 58 def render(self, *args, **kwargs):1 unmodified line60 if self.generate_func is None:61 ns = {}62 exec self.code in ns63 self.generate_func = ns['generate']56- result = []64 ctx = self.environment.context_class(self.environment, *args, **kwargs)58- self.generate_func(ctx, result.append)59- return u''.join(result)65+ return u''.join(self.generate_func(ctx))66 67 68 class PythonTranslator(Translator):69 """136 unmodified lines206 # -- jinja nodes207 208 def handle_template(self, node):209 """204- Handle the overall template node. This node is the first node and ensures205- that we get the bootstrapping code. It also knows about inheritance206- information. It only occours as outer node, never in the tree itself.210+ Handle the overall template node. This node is the first node and211+ ensures that we get the bootstrapping code. It also knows about212+ inheritance information. It only occours as outer node, never in213+ the tree itself.214 """215 # if there is a parent template we parse the parent template and216 # update the blocks there. Once this is done we drop the current217 # template in favor of the new one. Do that until we found the218 # root template.219 requirements_todo = []220+ blocks = node.blocks.copy()221+ parent = None222+223 while node.extends is not None:224+ # handle all requirements but not those from the225+ # root template. The root template renders everything so226+ # there is no need for additional requirements227 if node not in requirements_todo:228 requirements_todo.append(node)229 217- tmpl = self.environment.loader.parse(node.extends.template,218- node.filename)219- # handle block inheritance220- for block in tmpl.blocks.itervalues():221- if block.name in node.blocks:222- block.replace(node.blocks[block.name])223- node = tmpl230+ # load the template we inherit from and add not known blocks231+ # to the block registry, make this template the new root.232+ parent = self.environment.loader.parse(node.extends.template,233+ node.filename)234+ for name, block in parent.blocks.iteritems():235+ if name not in blocks:236+ blocks[name] = block237 225- if tmpl not in requirements_todo:226- requirements_todo.append(node)238+ node = parent239 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:2 unmodified lines252 253 # bootstrapping code254 lines = [255 'from __future__ import division\n'238- 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n\n'239- 'def generate(context, write):\n'256+ 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n'257+ 'from jinja.utils import buffereater\n\n'258+ 'def generate(context):\n'259 ' # BOOTSTRAPPING CODE\n'260 ' environment = context.environment\n'261 ' get_attribute = environment.get_attribute\n'262 ' perform_test = environment.perform_test\n'263 ' apply_filters = environment.apply_filters\n'264 ' call_function = environment.call_function\n'265 ' call_function_simple = environment.call_function_simple\n'247- ' finish_var = environment.finish_var'266+ ' finish_var = environment.finish_var\n'267+ ' ctx_push = context.push\n'268+ ' ctx_pop = context.pop\n'269 ]270 self.indention = 1271 272 # we have requirements? add them here.15 unmodified lines288 ' return translator.gettext(s) % (r or {})\n'289 ' return translator.ngettext(s, p, r[n]) % (r or {})'290 )291 lines.append(rv)292+ lines.append(' if False:\n yield None')293 294 return '\n'.join(lines)295 296 def handle_template_text(self, node):297 """298 Handle data around nodes.299 """278- return self.indent('write(%r)' % node.text)300+ return self.indent('yield %r' % node.text)301 302 def handle_node_list(self, node):303 """304 In some situations we might have a node list. It's just10 unmodified lines315 clause a different behavior.316 """317 buf = []318 write = lambda x: buf.append(self.indent(x))297- write('context.push()')319+ write('ctx_push()')320 321 # recursive loops322 if node.recursive:323 write('def forloop(seq):')324 self.indention += 1303- write('loopbuffer = []')304- write('write = loopbuffer.append')305- write('context[\'loop\'].push(seq)')306- write('for %s in context[\'loop\']:' %325+ write('for %s in context[\'loop\'].push(seq):' %326 self.handle_node(node.item),327 )328 329 # simple loops330 else:312- write('context[\'loop\'] = LoopContext(%s, context[\'loop\'], None)' %331+ write('context[\'loop\'] = loop = LoopContext(%s, context[\'loop\'], None)' %332 self.handle_node(node.seq))314- write('for %s in context[\'loop\']:' %333+ write('for %s in loop:' %334 self.handle_node(node.item)335 )336 337 # handle real loop code1 unmodified line339 buf.append(self.handle_node(node.body))340 self.indention -= 1341 342 # else part of loop324- if node.else_ is not None:343+ if node.else_:344 write('if not context[\'loop\'].iterated:')345 self.indention += 1346 buf.append(self.handle_node(node.else_))347 self.indention -= 1348 349 # call recursive for loop!350 if node.recursive:351 write('context[\'loop\'].pop()')333- write('return u\'\'.join(loopbuffer)')352+ write('if False:')353+ self.indention += 1354+ write('yield None')355+ self.indention -= 2356+ write('context[\'loop\'] = LoopContext(None, context[\'loop\'], buffereater(forloop))')357+ write('for item in forloop(%s):' % self.handle_node(node.seq))358+ self.indention += 1359+ write('yield item')360 self.indention -= 1335- write('context[\'loop\'] = LoopContext(None, context[\'loop\'], forloop)')336- write('write(forloop(%s))' % self.handle_node(node.seq))361 338- write('context.pop()')362+ write('ctx_pop()')363 return '\n'.join(buf)364 365 def handle_if_condition(self, node):366 """38 unmodified lines405 hardcoded = False406 self.indention -= 1407 408 if hardcoded:385- write('write(finish_var(context.current[%r].cycle()))' % name)409+ write('yield finish_var(context.current[%r].cycle())' % name)410 else:387- write('write(finish_var(context.current[%r].cycle(%s)))' % (411+ write('yield finish_var(context.current[%r].cycle(%s))' % (412 name,413 self.handle_node(node.seq)414 ))415 2 unmodified lines418 def handle_print(self, node):419 """420 Handle a print statement.421 """398- return self.indent('write(finish_var(%s))' % self.handle_node(node.variable))422+ return self.indent('yield finish_var(%s)' % self.handle_node(node.variable))423 424 def handle_macro(self, node):425 """426 Handle macro declarations.427 """428 buf = []429 write = lambda x: buf.append(self.indent(x))430 407- args = []408- defaults = []409- for name, n in node.arguments:410- args.append('context[\'%s\']' % name)411- if n is None:412- defaults.append('Undefined')413- else:414- defaults.append(self.handle_node(n))415-431 write('def macro(*args):')432 self.indention += 1418- write('context.push()')419- write('%s = (args + %s[len(args):])' % (_to_tuple(args), _to_tuple(defaults)))420- write('macrobuffer = []')421- write('write = macrobuffer.append')433+434+ if node.arguments:435+ write('argcount = len(args)')436+ tmp = []437+ for idx, (name, n) in enumerate(node.arguments):438+ tmp.append('\'%s\': (argcount > %d and (args[%d],) or (%s,))[0]' % (439+ name,440+ idx,441+ idx,442+ n is None and 'Undefined' or self.handle_node(n)443+ ))444+ write('ctx_push({%s})' % ', '.join(tmp))445+ else:446+ write('ctx_push()')447+448 buf.append(self.handle_node(node.body))423- write('context.pop()')424- write('return u\'\'.join(macrobuffer)')425- self.indention -= 1426- buf.append(self.indent('context[%r] = macro' % node.name))449+ write('ctx_pop()')450+ write('if False:')451+ self.indention += 1452+ write('yield False')453+ self.indention -= 2454+ buf.append(self.indent('context[%r] = buffereater(macro)' % node.name))455 456 return '\n'.join(buf)457 458 def handle_set(self, node):12 unmodified lines471 buf = []472 write = lambda x: buf.append(self.indent(x))473 write('def filtered():')474 self.indention += 1447- write('context.push()')448- write('buffer = []')449- write('write = buffer.append')475+ write('ctx_push()')476 buf.append(self.handle_node(node.body))451- write('context.pop()')452- write('return u\'\'.join(buffer)')453- self.indention -= 1454- write('write(%s)' % self.filter('filtered()', node.filters))477+ write('ctx_pop()')478+ write('if False:')479+ self.indention += 1480+ write('yield None')481+ self.indention -= 2482+ write('yield %s' % self.filter('u\'\'.join(filtered())', node.filters))483 return '\n'.join(buf)484 485 def handle_block(self, node):486 """14 unmodified lines501 write('# BLOCK FROM %r, LINE %s' % (502 node.filename or '?',503 node.lineno504 ))477- write('context.push()')505+ write('ctx_push()')506 buf.append(self.handle_node(node.body))479- write('context.pop()')507+ write('ctx_pop()')508 buf.append(self.indent('# END OF BLOCK'))509 return '\n'.join(buf)510 511 def handle_include(self, node):21 unmodified lines533 ))534 replacements = '{%s}' % ', '.join(replacements)535 else:536 replacements = 'None'509- return self.indent('write(translate(%r, %r, %r, %s))' % (537+ return self.indent('yield translate(%r, %r, %r, %s)' % (538 node.singular,539 node.plural,540 node.indicator,541 replacements92 unmodified lines634 def handle_getattr(self, node):635 """636 Handle hardcoded attribute access. foo.bar637 """638+ expr = node.expr639+640+ # chain getattrs for speed reasons641+ path = [repr(node.attrname)]642+ while node.expr.__class__ is ast.Getattr:643+ path.append(repr(node.attrname))644+ node = node.expr645+610- return 'get_attribute(%s, %r)' % (646+ return 'get_attribute(%s, %s)' % (647 self.handle_node(node.expr),612- node.attrname648+ _to_tuple(path)649 )650 651 def handle_ass_tuple(self, node):652 """178 unmodified linesmodified:jinja/datastructure.py+24 added-21 removed
7 unmodified lines8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-# python2.3 compatibility. do not use this method for anything else13-# then context reversing.14-try:15- _reversed = reversed16-except NameError:17- def _reversed(c):18- return c[::-1]19-12 # sets13 try:14 set15 except NameError:16 from sets import Set as set17 18+from jinja.exceptions import TemplateRuntimeError19 20+21 class UndefinedType(object):22 """23 An object that does not exist.24 """78 unmodified lines103 def __repr__(self):104 return 'Markup(%s)' % unicode.__repr__(self)105 106 113-safe_types = set([Markup, int, long, float])114-115-107 class Context(object):108 """109 Dict like object.110 """111 112 def __init__(self, _environment_, *args, **kwargs):113 self.environment = _environment_123- self._stack = [self.environment.globals, dict(*args, **kwargs), {}]114+ self._stack = [_environment_.globals, dict(*args, **kwargs), {}]115 self.globals, self.initial, self.current = self._stack116 117 # cache object used for filters and tests118 self.cache = {}2 unmodified lines121 """Return the translator for i18n."""122 return FakeTranslator()123 124 def pop(self):134- if len(self._stack) <= 2:135- raise ValueError('cannot pop initial layer')125+ """Pop the last layer from the stack and return it."""126 rv = self._stack.pop()127 self.current = self._stack[-1]128 return rv129 130 def push(self, data=None):131+ """Push a new dict or empty layer to the stack and return that layer"""132+ data = data or {}141- self._stack.append(data or {})133+ self._stack.append(data)134 self.current = self._stack[-1]135+ return data136 137 def to_dict(self):145- """146- Convert the context into a dict. This skips the globals.147- """138+ """Convert the context into a dict. This skips the globals."""139 result = {}140 for layer in self._stack[1:]:141 for key, value in layer.iteritems():142 result[key] = value2 unmodified lines145 def __getitem__(self, name):146 # don't give access to jinja internal variables147 if name.startswith('::'):148 return Undefined158- for d in _reversed(self._stack):149+ # because the stack is usually quite small we better use [::-1]150+ # which is faster than reversed() somehow.151+ for d in self._stack[::-1]:152 if name in d:153 rv = d[name]154 if isinstance(rv, Deferred):155 rv = rv(self, name)163- # never tough the globals!156+ # never touch the globals!157 if d is self.globals:158 self.initial[name] = rv159 else:160 d[name] = rv32 unmodified lines193 if seq is not None:194 self.push(seq)195 196 def push(self, seq):197+ """198+ Push a sequence to the loop stack. This is used by the199+ recursive for loop.200+ """201 if seq in (Undefined, None):202 seq = ()203 self._stack.append({204 'index': -1,205 'seq': seq,206 'length': len(seq)207 })208+ return self209 210 def pop(self):211+ """Remove the last layer from the loop stack."""212 return self._stack.pop()213 214 iterated = property(lambda s: s._stack[-1]['index'] > -1)215 index0 = property(lambda s: s._stack[-1]['index'])17 unmodified lines233 234 def __call__(self, seq):235 if self.loop_function is not None:236 return self.loop_function(seq)238- return Undefined237+ raise TemplateRuntimeError('Loops are just callable if defined with '238+ 'the "recursive" modifier.')239 240 241 class CycleContext(object):242 """1 unmodified line244 """245 246 def __init__(self, seq=None):247 self.lineno = -1248+ # bind the correct helper function based on the constructor signature249 if seq is not None:250 self.seq = seq251 self.length = len(seq)252 self.cycle = self.cycle_static253 else:254 self.cycle = self.cycle_dynamic255 256 def cycle_static(self):257+ """Helper function for static cycling."""258 self.lineno = (self.lineno + 1) % self.length259 return self.seq[self.lineno]260 261 def cycle_dynamic(self, seq):262+ """Helper function for dynamic cycling."""263 self.lineno = (self.lineno + 1) % len(seq)264 return seq[self.lineno]265 266 64 unmodified linesmodified:jinja/environment.py+24 added-14 removed
10 unmodified lines11 import re12 from jinja.lexer import Lexer13 from jinja.parser import Parser14 from jinja.loaders import LoaderWrapper15-from jinja.datastructure import Undefined, Context15+from jinja.datastructure import Undefined, Context, Markup16 from jinja.utils import escape17 from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException18 from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19 71 unmodified lines91 def to_unicode(self, value):92 """93 Convert a value to unicode with the rules defined on the environment.94 """95+ if value in (None, Undefined):96+ return u''95- if isinstance(value, unicode):97+ elif isinstance(value, unicode):98 return value99 else:100 try:101 return unicode(value)30 unmodified lines132 if invert:133 return not rv134 return bool(rv)135 134- def get_attribute(self, obj, name):136+ def get_attribute(self, obj, attributes):137 """136- Get the attribute name from obj.138+ Get some attributes from an object.139 """140+ node = obj141+ for name in attributes:138- try:139- return obj[name]140- except (TypeError, KeyError, IndexError):141- if hasattr(obj, name):142+ try:143+ node = node[name]144+ except (TypeError, KeyError, IndexError):145+ if not hasattr(obj, 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)145- return getattr(obj, name)146- return Undefined150+ node = getattr(obj, name)151+ return node152 153 def call_function(self, f, args, kwargs, dyn_args, dyn_kwargs):154 """155 Function call helper. Called for all functions that are passed11 unmodified lines167 def call_function_simple(self, f):168 """169 Function call without arguments.170 """166- if getattr(f, 'jinja_unsafe_call', False):171+ if getattr(f, 'jinja_unsafe_call', False) or \172+ getattr(f, 'alters_data', False):173 raise SecurityException('unsafe function %r called' % f.__name__)174 return f()175 176 def finish_var(self, value):1 unmodified line178 As long as no write_var function is passed to the template179 evaluator the source generated by the python translator will180 call this function for all variables.181 """176- if value is Undefined:182+ if value is Undefined or value is None:183 return u''184+ elif isinstance(value, (int, float, Markup, bool)):185+ return unicode(value)186+ elif not isinstance(value, unicode):187+ value = self.to_unicode(value)178- elif self.auto_escape:188+ if self.auto_escape:189 return escape(value, True)180- return unicode(value)190+ return valuemodified:jinja/exceptions.py-4 removed
60 unmodified lines61 """62 Raised by the template engine if a tag encountered an error when63 rendering.64 """65-66- def __init__(self, message, lineno):67- RuntimeError.__init__(self, message)68- self.lineno = linenomodified:jinja/loaders.py+103 added-17 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 import codecs13+import sha14+import time15 from os import path16+from threading import Lock17 from jinja.parser import Parser15-from jinja.translators.python import PythonTranslator18+from jinja.translators.python import PythonTranslator, Template19 from jinja.exceptions import TemplateNotFound20+from jinja.utils import CacheDict21 22 23 __all__ = ['FileSystemLoader']24 5 unmodified lines30 return path.join(searchpath, path.sep.join([p for p in name.split('/')31 if p and p[0] != '.']))32 33 34+def get_template_cachename(cachepath, name):35+ """36+ Return the filename for a cached file.37+ """38+ return path.join(cachepath, 'jinja_%s.cache' %39+ sha.new('jinja(%s)tmpl' % name).hexdigest())40+41+42 class LoaderWrapper(object):43 """44 Wraps a loader so that it's bound to an environment.45 """52 unmodified lines98 99 =================== =================================================100 ``searchpath`` String with the path to the templates on the101 filesystem.90- ``use_cache`` Set this to ``True`` to enable memory caching.102+ ``use_memcache`` Set this to ``True`` to enable memory caching.103 This is usually a good idea in production mode,104 but disable it during development since it won't105 reload template changes automatically.106 This only works in persistent environments like107 FastCGI.96- ``cache_size`` Number of template instance you want to cache.108+ ``memcache_size`` Number of template instance you want to cache.109 Defaults to ``40``.110+ ``cache_folder`` Set this to an existing directory to enable111+ caching of templates on the file system. Note112+ that this only affects templates transformed113+ into python code. Default is ``None`` which means114+ that caching is disabled.115+ ``auto_reload`` Set this to `False` for a slightly better116+ performance. In that case Jinja won't check for117+ template changes on the filesystem.118 =================== =================================================119 """120 101- def __init__(self, searchpath, use_cache=False, cache_size=40):121+ def __init__(self, searchpath, use_memcache=False, memcache_size=40,122+ cache_folder=None, auto_reload=True):123 self.searchpath = searchpath103- self.use_cache = use_cache104- self.cache_size = cache_size105- self.cache = {}124+ self.use_memcache = use_memcache125+ if use_memcache:126+ self.memcache = CacheDict(memcache_size)127+ else:128+ self.memcache = None129+ self.cache_folder = cache_folder130+ self.auto_reload = auto_reload131+ self._times = {}132+ self._lock = Lock()133 134 def get_source(self, environment, name, parent):135+ """136+ Get the source code of a template.137+ """138 filename = get_template_filename(self.searchpath, name)139 if path.exists(filename):140 f = codecs.open(filename, 'r', environment.template_charset)141 try:3 unmodified lines145 else:146 raise TemplateNotFound(name)147 148 def parse(self, environment, name, parent):149+ """150+ Load and parse a template151+ """152 source = self.get_source(environment, name, parent)153 return Parser(environment, source, name).parse()154 155 def load(self, environment, name, translator):123- if self.use_cache:124- key = (name, translator)125- if key in self.cache:126- return self.cache[key]127- if len(self.cache) >= self.cache_size:128- self.cache.clear()129- rv = translator.process(environment, self.parse(environment, name, None))130- if self.use_cache:131- self.cache[key] = rv132- return rv156+ """157+ Load, parse and translate a template.158+ """159+ self._lock.acquire()160+ try:161+ # caching is only possible for the python translator. skip162+ # all other translators163+ if translator is PythonTranslator:164+ tmpl = None165+166+ # auto reload enabled? check for the last change of the template167+ if self.auto_reload:168+ last_change = path.getmtime(get_template_filename(self.searchpath, name))169+ else:170+ last_change = None171+172+ # check if we have something in the memory cache and the173+ # memory cache is enabled.174+ if self.use_memcache and name in self.memcache:175+ tmpl = self.memcache[name]176+ if last_change is not None and last_change > self._times[name]:177+ tmpl = None178+179+ # if diskcache is enabled look for an already compiled template180+ if self.cache_folder is not None:181+ cache_filename = get_template_cachename(self.cache_folder, name)182+183+ # there is a up to date compiled template184+ if tmpl is not None and last_change is None:185+ try:186+ cache_time = path.getmtime(cache_filename)187+ except OSError:188+ cache_time = 0189+ if last_change >= cache_time:190+ f = file(cache_filename, 'rb')191+ try:192+ tmpl = Template.load(environment, f)193+ finally:194+ f.close()195+196+ # no template so far, parse, translate and compile it197+ elif tmpl is None:198+ tmpl = translator.process(environment, self.parse(environment, name, None))199+200+ # save the compiled template201+ f = file(cache_filename, 'wb')202+ try:203+ tmpl.dump(f)204+ finally:205+ f.close()206+207+ # if memcaching is enabled push the template208+ if tmpl is not None:209+ if self.use_memcache:210+ self._times[name] = time.time()211+ self.memcache[name] = tmpl212+ return tmpl213+214+ # if we reach this point we don't have caching enabled or translate215+ # to something else than python216+ return translator.process(environment, self.parse(environment, name, None))217+ finally:218+ self._lock.release()modified:jinja/nodes.py+3 added-2 removed
188 unmodified lines189 self.body = body190 191 def get_items(self):192 result = [self.name]193+ if self.arguments:193- for item in self.arguments:194- result.extend(item)194+ for item in self.arguments:195+ result.extend(item)196 result.append(self.body)197 return result198 199 def __repr__(self):132 unmodified linesmodified:jinja/parser.py+6 added-2 removed
200 unmodified lines201 202 if ast.varargs or ast.kwargs:203 raise TemplateSyntaxError('variable length macro signature '204 'not allowed.', lineno)205+ if ast.argnames:205- defaults = [None] * (len(ast.argnames) - len(ast.defaults)) + ast.defaults206- return nodes.Macro(lineno, ast.name, zip(ast.argnames, defaults), body)206+ defaults = [None] * (len(ast.argnames) - len(ast.defaults)) + ast.defaults207+ args = zip(ast.argnames, defaults)208+ else:209+ args = None210+ return nodes.Macro(lineno, ast.name, args, body)211 212 def handle_block_directive(self, lineno, gen):213 """214 Handle block directives used for inheritance.279 unmodified linesmodified:jinja/utils.py+143 added-5 removed
7 unmodified lines8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import re12+from types import MethodType, FunctionType13 from jinja.nodes import Trans13-from jinja.datastructure import safe_types, Markup14+from jinja.datastructure import Markup15 16+try:17+ from collections import deque18+except ImportError:19+ deque = None20 21+22 _escape_pairs = {23 '&': '&',24 '<': '<',25 '>': '>',7 unmodified lines33 34 35 def escape(x, attribute=False):36 """31- Escape an object x which is converted to unicode first.37+ Escape an object x.38 """33- if type(x) in safe_types:34- return x39 return Markup(_escape_res[not attribute].sub(lambda m:36- _escape_pairs[m.group()], unicode(x)))40+ _escape_pairs[m.group()], x))41 42 43 def find_translations(environment, source):44 """6 unmodified lines51 node = queue.pop()52 if node.__class__ is Trans:53 yield node.lineno, node.singular, node.plural54 queue.extend(node.getChildNodes())55+56+57+def buffereater(f):58+ """59+ Used by the python translator to capture output of substreams.60+ (macros, filter sections etc)61+ """62+ def wrapped(*args, **kwargs):63+ return u''.join(f(*args, **kwargs))64+ return wrapped65+66+67+class CacheDict(object):68+ """69+ A dict like object that stores a limited number of items and forgets70+ about the least recently used items::71+72+ >>> cache = CacheDict(3)73+ >>> cache['A'] = 074+ >>> cache['B'] = 175+ >>> cache['C'] = 276+ >>> len(cache)77+ 378+ 79+ If we now access 'A' again it has a higher priority than B::80+81+ >>> cache['A']82+ 083+84+ If we add a new item 'D' now 'B' will disappear::85+86+ >>> cache['D'] = 387+ >>> len(cache)88+ 389+ >>> 'B' in cache90+ False91+92+ If you iterate over the object the most recently used item will be93+ yielded First::94+95+ >>> for item in cache:96+ ... print item97+ D98+ A99+ C100+101+ If you want to iterate the other way round use ``reverse(cache)``.102+103+ Implementation note: This is not a nice way to solve that problem but104+ for smaller capacities it's faster than a linked list.105+ Perfect for template environments where you don't expect too many106+ different keys.107+ """108+109+ def __init__(self, capacity):110+ self.capacity = capacity111+ self._mapping = {}112+113+ # use a deque here if possible114+ if deque is not None:115+ self._queue = deque()116+ self._popleft = self._queue.popleft117+ # python2.3, just use a list118+ else:119+ self._queue = []120+ pop = self._queue.pop121+ self._popleft = lambda: pop(0)122+ # alias all queue methods for faster lookup123+ self._pop = self._queue.pop124+ self._remove = self._queue.remove125+ self._append = self._queue.append126+127+ def copy(self):128+ rv = CacheDict(self.capacity)129+ rv._mapping.update(self._mapping)130+ rv._queue = self._queue[:]131+ return rv132+133+ def get(self, key, default=None):134+ if key in self:135+ return self[key]136+ return default137+138+ def setdefault(self, key, default=None):139+ if key in self:140+ return self[key]141+ self[key] = default142+ return default143+144+ def clear(self):145+ self._mapping.clear()146+ del self._queue[:]147+148+ def __contains__(self, key):149+ return key in self._mapping150+151+ def __len__(self):152+ return len(self._mapping)153+154+ def __repr__(self):155+ return '<%s %r>' % (156+ self.__class__.__name__,157+ self._mapping158+ )159+160+ def __getitem__(self, key):161+ rv = self._mapping[key]162+ if self._queue[-1] != key:163+ self._remove(key)164+ self._append(key)165+ return rv166+167+ def __setitem__(self, key, value):168+ if key in self._mapping:169+ self._remove(key)170+ elif len(self._mapping) == self.capacity:171+ del self._mapping[self._popleft()]172+ self._append(key)173+ self._mapping[key] = value174+175+ def __delitem__(self, key):176+ del self._mapping[key]177+ self._remove(key)178+179+ def __iter__(self):180+ try:181+ return reversed(self._queue)182+ except NameError:183+ return iter(self._queue[::-1])184+185+ def __reversed__(self):186+ return iter(self._queue)187+188+ __copy__ = copyadded:tests/templates/a.html+9 added
1+{% block block1 %}from template a.html{% endblock %}2+{% block block2 %}from template a.html{% endblock %}3+{% block block3 %}from template a.html{% endblock %}4+{% block block4 %}5+ nested block from template a.html6+ {% block block5 %}7+ contents of the nested block from a.html8+ {% endblock %}9+{% endblock %}added:tests/templates/b.html+3 added
1+{% extends 'a.html' %}2+{% block block1 %}from template b.html{% endblock %}3+{% block block5 %}contents of nested block from b.html{% endblock %}added:tests/templates/c.html+3 added
1+{% extends 'b.html' %}2+{% block block2 %}from template c.html{% endblock %}3+{% block block3 %}from template c.html{% endblock %}modified:tests/inheritance.py+2 added-7 removed
2 unmodified lines3 4 from jinja.parser import Parser5 from jinja.translators.python import PythonTranslator6 7-print PythonTranslator(e, e.loader.parse('index.html')).translate()8-9-tmpl = e.loader.load('index.html')10-print tmpl.render(navigation_items=[{7+tmpl = e.loader.load('c.html')8+print tmpl.render()11- 'url': '/',12- 'caption': 'Index'13-}])added:tests/layout.py+13 added
1+from jinja import Environment, FileSystemLoader2+e = Environment(loader=FileSystemLoader('templates'))3+4+from jinja.parser import Parser5+from jinja.translators.python import PythonTranslator6+7+print PythonTranslator(e, e.loader.parse('index.html')).translate()8+9+tmpl = e.loader.load('index.html')10+print tmpl.render(navigation_items=[{11+ 'url': '/',12+ 'caption': 'Index'13+}])modified:www/generate.py+2 added-1 removed
12 unmodified lines13 14 15 formatter = HtmlFormatter(cssclass='syntax', encoding=None, style='pastie')16 17-env = Environment('<%', '%>', '<%=', '%>', loader=FileSystemLoader('.'), trim_blocks=True)17+env = Environment('<%', '%>', '<%=', '%>', loader=FileSystemLoader('.',18+ cache_folder='/tmp'), trim_blocks=True)19 env.filters['pygmentize'] = stringfilter(lambda v, l:20 highlight(v.strip(), get_lexer_by_name(l), formatter))21 22 25 unmodified lines