Various cleanups and added custom cycler.
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 673aa88 · Browse files · 16 files·+190 added−78 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+190 added−78 removed
- tests:+25 added−16 removed
- other:+165 added−62 removed
Provenance
- Commit
ccae055- Tree
eb4492c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
673aa88
16 files changed+190 added−78 removed
modified:docs/templates.rst+42 added
480 unmodified lines481 {% for row in rows %}482 <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>483 {% endfor %}484 485+With Jinja 2.1 an extra `cycle` helper exists that allows loop-unbound486+cycling. For more information have a look at the :ref:`builtin-globals`.487+488 .. _loop-filtering:489 490 Unlike in Python it's not possible to `break` or `continue` in a loop. You491 can however filter the sequence during iteration which allows you to skip509 unmodified lines1001 ---------------------1002 1003 .. jinjatests::1004 1005+.. _builtin-globals:1006 1007 List of Global Functions1008 ------------------------1009 31 unmodified lines1041 1042 A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same1043 as ``dict(foo='bar')``.1044 1045+.. class:: cycler(\*items)1046 1047+ The cycler allows you to cycle among values similar to how `loop.cycle`1048+ works. Unlike `loop.cycle` however you can use this cycler outside of1049+ loops or over multiple loops.1050+1051+ This is for example very useful if you want to show a list of folders and1052+ files, with the folders on top, but both in the same list with alteranting1053+ row colors.1054+1055+ The following example shows how `cycler` can be used::1056+1057+ {% set row_class = cycler('odd', 'even') %}1058+ <ul class="browser">1059+ {% for folder in folders %}1060+ <li class="folder {{ row_class.next() }}">{{ folder|e }}</li>1061+ {% endfor %}1062+ {% for filename in files %}1063+ <li class="file {{ row_class.next() }}">{{ filename|e }}</li>1064+ {% endfor %}1065+ </ul>1066+1067+ A cycler has the following attributes and methods:1068+1069+ .. method:: reset()1070+1071+ Resets the cycle to the first item.1072+1073+ .. method:: next()1074+1075+ Goes one item a head and returns the then current item.1076+1077+ .. attribute:: current1078+1079+ Returns the current item.1080+ 1081+ **new in Jinja 2.1**1082+1083+1084 Extensions1085 ----------1086 1087 The following sections cover the built-in Jinja2 extensions that may be96 unmodified linesmodified:jinja2/__init__.py+3 added-2 removed
57 unmodified lines58 59 __all__ = [60 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',61 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',62- 'ChoiceLoader', 'Undefined', 'DebugUndefined', 'StrictUndefined',63- 'TemplateError', 'UndefinedError', 'TemplateNotFound',62+ 'ChoiceLoader', 'BytecodeCache', 'FileSystemBytecodeCache',63+ 'MemcachedBytecodeCache', 'Undefined', 'DebugUndefined',64+ 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound',65 'TemplateSyntaxError', 'TemplateAssertionError', 'environmentfilter',66 'contextfilter', 'Markup', 'escape', 'environmentfunction',67 'contextfunction', 'clear_caches', 'is_undefined'68 ]modified:jinja2/bccache.py+4 added-5 removed
22 unmodified lines23 try:24 from hashlib import sha125 except ImportError:26 from sha import new as sha127+from jinja2.utils import open_if_exists28 29 30 bc_version = 131 bc_magic = 'j2' + pickle.dumps(bc_version, 2)161 unmodified lines193 def _get_cache_filename(self, bucket):194 return path.join(self.directory, self.pattern % bucket.key)195 196 def load_bytecode(self, bucket):196- filename = self._get_cache_filename(bucket)197- if path.exists(filename):198- f = file(filename, 'rb')197+ f = open_if_exists(self._get_cache_filename(bucket), 'rb')198+ if f is not None:199 try:200 bucket.load_bytecode(f)201 finally:202 f.close()203 204 def dump_bytecode(self, bucket):205- filename = self._get_cache_filename(bucket)206- f = file(filename, 'wb')205+ f = file(self._get_cache_filename(bucket), 'wb')206 try:207 bucket.write_bytecode(f)208 finally:209 f.close()71 unmodified linesmodified:jinja2/debug.py-18 removed
33 unmodified lines34 35 return exc_info[:2] + (result_tb or initial_tb,)36 37 38-def translate_syntax_error(error):39- """When passed a syntax error it will generate a new traceback with40- more debugging information.41- """42- filename = error.filename43- if filename is None:44- filename = '<template>'45- elif isinstance(filename, unicode):46- filename = filename.encode('utf-8')47- code = compile('\n' * (error.lineno - 1) + 'raise __jinja_exception__',48- filename, 'exec')49- try:50- exec code in {'__jinja_exception__': error}51- except:52- exc_info = sys.exc_info()53- return exc_info[:2] + (exc_info[2].tb_next,)54-55-38 def fake_exc_info(exc_info, filename, lineno, tb_back=None):39 """Helper for `translate_exception`."""40 exc_type, exc_value, tb = exc_info41 132 unmodified linesmodified:jinja2/defaults.py+3 added-2 removed
6 unmodified lines7 8 :copyright: 2007-2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-from jinja2.utils import generate_lorem_ipsum11+from jinja2.utils import generate_lorem_ipsum, Cycler12 13 14 # defaults for the parser / lexer15 BLOCK_START_STRING = '{%'12 unmodified lines28 from jinja2.tests import TESTS as DEFAULT_TESTS29 DEFAULT_NAMESPACE = {30 'range': xrange,31 'dict': lambda **kw: kw,32- 'lipsum': generate_lorem_ipsum32+ 'lipsum': generate_lorem_ipsum,33+ 'cycler': Cycler34 }35 36 37 # export all constants1 unmodified linemodified:jinja2/environment.py+21 added-4 removed
46 unmodified lines47 return {}48 return LRUCache(size)49 50 51+def copy_cache(cache):52+ """Create an empty copy of the given cache."""53+ if cache is None:54+ return Noe55+ elif type(cache) is dict:56+ return {}57+ return LRUCache(cache.capacity)58+59+60 def load_extensions(environment, extensions):61 """Load the extensions from the list and bind it to the environment.62 Returns a dict of instanciated environments.63 """229 unmodified lines293 setattr(rv, key, value)294 295 if cache_size is not missing:296 rv.cache = create_cache(cache_size)297+ else:298+ rv.cache = copy_cache(self.cache)299 300 rv.extensions = {}301 for key, value in self.extensions.iteritems():302 rv.extensions[key] = value.bind(rv)47 unmodified lines350 filename = filename.encode('utf-8')351 try:352 return Parser(self, source, name, filename).parse()353 except TemplateSyntaxError, e:343- from jinja2.debug import translate_syntax_error344- exc_type, exc_value, tb = translate_syntax_error(e)345- raise exc_type, exc_value, tb354+ e.source = source355+ raise e356 357 def lex(self, source, name=None, filename=None):358 """Lex the given sourcecode and return a generator that yields359 tokens as tuples in the form ``(lineno, token_type, value)``.3 unmodified lines363 This does not perform preprocessing. If you want the preprocessing364 of the extensions to be applied you have to filter source through365 the :meth:`preprocess` method.366 """367+ source = unicode(source)368+ try:357- return self.lexer.tokeniter(unicode(source), name, filename)369+ return self.lexer.tokeniter(source, name, filename)370+ except TemplateSyntaxError, e:371+ e.source = source372+ raise e373 374 def preprocess(self, source, name=None, filename=None):375 """Preprocesses the source with all extensions. This is automatically376 called for all parsing and compiling methods but *not* for :meth:`lex`231 unmodified lines608 parent = vars609 else:610 parent = dict(self.globals, **vars)611 if locals:612+ # if the parent is shared a copy should be created because613+ # we don't want to modify the dict passed614 if shared:615 parent = dict(parent)616 for key, value in locals.iteritems():617 if key[:2] == 'l_' and value is not missing:168 unmodified linesmodified:jinja2/exceptions.py+26 added-13 removed
24 unmodified lines25 class TemplateSyntaxError(TemplateError):26 """Raised to tell the user that there is a problem with the template."""27 28 def __init__(self, message, lineno, name=None, filename=None):29- if name is not None:30- extra = '%s, line %d' % (name.encode('utf-8'), lineno)31- else:32- extra = 'line %d' % lineno33- # if the message was provided as unicode we have to encode it34- # to utf-8 explicitly35- if isinstance(message, unicode):36- message = message.encode('utf-8')37- # otherwise make sure it's a in fact valid utf-838- else:39- message = message.decode('utf-8', 'ignore').encode('utf-8')40- TemplateError.__init__(self, '%s (%s)' % (message, extra))41- self.message = message29+ if not isinstance(message, unicode):30+ message = message.decode('utf-8', 'replace')31+ TemplateError.__init__(self, message.encode('utf-8'))32 self.lineno = lineno33 self.name = name34 self.filename = filename35+ self.source = None36+ self.message = message37 38+ def __unicode__(self):39+ location = 'line %d' % self.lineno40+ name = self.filename or self.name41+ if name:42+ location = 'File "%s", %s' % (name, location)43+ lines = [self.message, ' ' + location]44 45+ # if the source is set, add the line to the output46+ if self.source is not None:47+ try:48+ line = self.source.splitlines()[self.lineno - 1]49+ except IndexError:50+ line = None51+ if line:52+ lines.append(' ' + line.strip())53+54+ return u'\n'.join(lines)55+56+ def __str__(self):57+ return unicode(self).encode('utf-8')58+59+60 class TemplateAssertionError(TemplateSyntaxError):61 """Like a template syntax error, but covers cases where something in the62 template caused an error at compile time that wasn't necessarily caused63 by a syntax error. However it's a direct subclass of24 unmodified linesmodified:jinja2/filters.py+18 added-10 removed
337 unmodified lines338 339 {{ mytext|indent(2, true) }}340 indent by two spaces and indent the first line too.341 """342- indention = ' ' * width342+ indention = u' ' * width343+ rv = (u'\n' + indention).join(s.splitlines())344 if indentfirst:344- return u'\n'.join(indention + line for line in s.splitlines())345- return s.replace('\n', '\n' + indention)345+ rv = indention + rv346+ return rv347 348 349 def do_truncate(s, length=255, killwords=False, end='...'):350 """Return a truncated copy of the string. The length is specified297 unmodified lines648 649 See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.650 """651 try:651- value = getattr(obj, name)652- except AttributeError:653- return environment.undefined(obj=obj, name=name)654- if environment.sandboxed and not \655- environment.is_safe_attribute(obj, name, value):656- return environment.unsafe_undefined(obj, name)657- return value652+ name = str(name)653+ except UnicodeError:654+ pass655+ else:656+ try:657+ value = getattr(obj, name)658+ except AttributeError:659+ pass660+ else:661+ if environment.sandboxed and not \662+ environment.is_safe_attribute(obj, name, value):663+ return environment.unsafe_undefined(obj, name)664+ return value665+ return environment.undefined(obj=obj, name=name)666 667 668 FILTERS = {669 'attr': do_attr,46 unmodified linesmodified:jinja2/loaders.py+5 added-4 removed
12 unmodified lines13 from hashlib import sha114 except ImportError:15 from sha import new as sha116 from jinja2.exceptions import TemplateNotFound17-from jinja2.utils import LRUCache17+from jinja2.utils import LRUCache, open_if_exists18 19 20 def split_template_path(template):21 """Split a path into segments and perform a sanity check. If it detects119 unmodified lines141 def get_source(self, environment, template):142 pieces = split_template_path(template)143 for searchpath in self.searchpath:144 filename = path.join(searchpath, *pieces)145- if not path.isfile(filename):145+ f = open_if_exists(filename)146+ if f is None:147 continue147- f = file(filename)148 try:149 contents = f.read().decode(self.encoding)150 finally:151 f.close()18 unmodified lines170 """171 172 def __init__(self, package_name, package_path='templates',173 encoding='utf-8'):174- from pkg_resources import DefaultProvider, ResourceManager, get_provider174+ from pkg_resources import DefaultProvider, ResourceManager, \175+ get_provider176 provider = get_provider(package_name)177 self.encoding = encoding178 self.manager = ResourceManager()179 self.filesystem_bound = isinstance(provider, DefaultProvider)121 unmodified linesmodified:jinja2/runtime.py+4 added-4 removed
163 unmodified lines164 self.name165 )166 167 168-# register the context as mutable mapping if possible168+# register the context as mapping if possible169 try:170- from collections import MutableMapping171- MutableMapping.register(Context)170+ from collections import Mapping171+ Mapping.register(Context)172 except ImportError:173 pass174 175 232 unmodified lines408 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \409 __int__ = __float__ = __complex__ = _fail_with_undefined_error410 411 def __str__(self):412- return self.__unicode__().encode('utf-8')412+ return unicode(self).encode('utf-8')413 414 def __unicode__(self):415 return u''416 67 unmodified linesmodified:jinja2/utils.py+37 added
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 import sys13+import errno14 try:15 from thread import allocate_lock16 except ImportError:17 from dummy_thread import allocate_lock155 unmodified lines173 if not silent:174 raise175 176 177+def open_if_exists(filename, mode='r'):178+ """Returns a file descriptor for the filename if that file exists,179+ otherwise `None`.180+ """181+ try:182+ return file(filename, mode)183+ except IOError, e:184+ if e.errno not in (errno.ENOENT, errno.EISDIR):185+ raise186+187+188 def pformat(obj, verbose=False):189 """Prettyprint an object. Either use the `pretty` library or the190 builtin `pprint`.191 """467 unmodified lines659 except ImportError:660 pass661 662 663+class Cycler(object):664+ """A cycle helper for templates."""665+666+ def __init__(self, *items):667+ if not items:668+ raise RuntimeError('at least one item has to be provided')669+ self.items = items670+ self.reset()671+672+ def reset(self):673+ """Resets the cycle."""674+ self.pos = 0675+676+ @property677+ def current(self):678+ """Returns the current item."""679+ return self.items[self.pos]680+681+ def next(self):682+ """Goes one item ahead and returns it."""683+ rv = self.current684+ self.pos = (self.pos + 1) % len(self.items)685+ return rv686+687+688 # we have to import it down here as the speedups module imports the689 # markup type which is define above.690 try:691 from jinja2._speedups import escape, soft_unicode37 unmodified linesmodified:tests/test_debug.py+2 added-2 removed
29 unmodified lines30 test_syntax_error = '''31 >>> tmpl = MODULE.env.get_template('syntaxerror.html')32 Traceback (most recent call last):33 ...34+TemplateSyntaxError: unknown tag 'endif'34- File "loaderres/templates/syntaxerror.html", line 4, in <module>35+ File "loaderres/templates/syntaxerror.html", line 436 {% endif %}36-TemplateSyntaxError: unknown tag 'endif' (syntaxerror.html, line 4)37 '''modified:tests/test_filters.py+2 added-2 removed
150 unmodified lines151 def test_indent(env):152 tmpl = env.from_string(INDENT)153 text = '\n'.join([' '.join(['foo', 'bar'] * 2)] * 2)154 out = tmpl.render(foo=text)155- assert out == 'foo bar foo bar\n foo bar foo bar| ' \156- 'foo bar foo bar\n foo bar foo bar'155+ assert out == ('foo bar foo bar\n foo bar foo bar| '156+ 'foo bar foo bar\n foo bar foo bar')157 158 159 def test_int(env):160 tmpl = env.from_string(INT)171 unmodified linesmodified:tests/test_security.py+8 added-12 removed
9 unmodified lines10 from jinja2 import Environment11 from jinja2.sandbox import SandboxedEnvironment, \12 ImmutableSandboxedEnvironment, unsafe13 from jinja2 import Markup, escape14-from jinja2.exceptions import SecurityError14+from jinja2.exceptions import SecurityError, TemplateSyntaxError15 16 17 class PrivateStuff(object):18 42 unmodified lines61 SecurityError: access to attribute '__class__' of 'int' object is unsafe.62 '''63 64 65-test_restricted = '''66->>> env = MODULE.SandboxedEnvironment()67->>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")68-Traceback (most recent call last):69- ...70-TemplateSyntaxError: expected token 'in', got '.' (line 1)71->>> env.from_string("{% for foo, bar.baz in seq %}...{% endfor %}")72-Traceback (most recent call last):73- ...74-TemplateSyntaxError: expected token 'in', got '.' (line 1)75-'''65+def test_restricted():66+ env = SandboxedEnvironment()67+ raises(TemplateSyntaxError, env.from_string,68+ "{% for item.attribute in seq %}...{% endfor %}")69+ raises(TemplateSyntaxError, env.from_string,70+ "{% for foo, bar.baz in seq %}...{% endfor %}")71 72 73 test_immutable_environment = '''74 >>> env = MODULE.ImmutableSandboxedEnvironment()6 unmodified lines81 ...82 SecurityError: access to attribute 'clear' of 'dict' object is unsafe.83 '''84 85+86 def test_markup_operations():87 # adding two strings should escape the unsafe one88 unsafe = '<script type="application/x-some-script">alert("foo");</script>'89 safe = Markup('<em>username</em>')49 unmodified linesmodified:tests/test_various.py+13 added
7 unmodified lines8 """9 import gc10 from py.test import raises11 from jinja2 import escape12+from jinja2.utils import Cycler13 from jinja2.exceptions import TemplateSyntaxError14 15 16 UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''67 unmodified lines84 tmpl = env.from_string('{% for item in seq %}|{{ item }}{% endfor %}')85 assert tmpl.render(seq=(None, 1, "foo")) == '||1|foo'86 tmpl = env.from_string('<{{ none }}>')87 assert tmpl.render() == '<>'88+89+90+def test_cycler():91+ items = 1, 2, 392+ c = Cycler(*items)93+ for item in items + items:94+ assert c.current == item95+ assert c.next() == item96+ c.next()97+ assert c.current == 298+ c.reset()99+ assert c.current == 1modified:CHANGES+2 added
35 unmodified lines36 37 - inclusions and imports "with context" forward all variables now, not only38 the initial context.39 40+- added a cycle helper called `cycle`.41+42 Version 2.043 -----------44 (codename jinjavitus, released on July 17th 2008)45 32 unmodified lines