Skip to content
Myr

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

16 files+190 added−78 removed

modified:docs/templates.rst+42 added
480 unmodified lines
481 {% for row in rows %}482 <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>483 {% endfor %}484485With Jinja 2.1 an extra `cycle` helper exists that allows loop-unbound486cycling. For more information have a look at the :ref:`builtin-globals`.487488.. _loop-filtering:489490Unlike in Python it's not possible to `break` or `continue` in a loop. You491can however filter the sequence during iteration which allows you to skip
509 unmodified lines
1001---------------------10021003.. jinjatests::10041005.. _builtin-globals:10061007List of Global Functions1008------------------------1009
31 unmodified lines
10411042 A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same1043 as ``dict(foo='bar')``.10441045.. class:: cycler(\*items)10461047 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.10501051 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.10541055 The following example shows how `cycler` can be used::10561057 {% 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>10661067 A cycler has the following attributes and methods:10681069 .. method:: reset()10701071 Resets the cycle to the first item.10721073 .. method:: next()10741075 Goes one item a head and returns the then current item.10761077 .. attribute:: current10781079 Returns the current item.1080 1081 **new in Jinja 2.1**108210831084Extensions1085----------10861087The following sections cover the built-in Jinja2 extensions that may be
96 unmodified lines
modified:jinja2/__init__.py+3 added-2 removed
57 unmodified lines
5859__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 lines
23try:24 from hashlib import sha125except ImportError:26 from sha import new as sha127from jinja2.utils import open_if_exists282930bc_version = 131bc_magic = 'j2' + pickle.dumps(bc_version, 2)
161 unmodified lines
193 def _get_cache_filename(self, bucket):194 return path.join(self.directory, self.pattern % bucket.key)195196 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()203204 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 lines
modified:jinja2/debug.py-18 removed
33 unmodified lines
3435 return exc_info[:2] + (result_tb or initial_tb,)363738def 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,)545538def 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 lines
modified:jinja2/defaults.py+3 added-2 removed
6 unmodified lines
78 :copyright: 2007-2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja2.utils import generate_lorem_ipsum11from jinja2.utils import generate_lorem_ipsum, Cycler121314# defaults for the parser / lexer15BLOCK_START_STRING = '{%'
12 unmodified lines
28from jinja2.tests import TESTS as DEFAULT_TESTS29DEFAULT_NAMESPACE = {30 'range': xrange,31 'dict': lambda **kw: kw,32 'lipsum': generate_lorem_ipsum32 'lipsum': generate_lorem_ipsum,33 'cycler': Cycler34}353637# export all constants
1 unmodified line
modified:jinja2/environment.py+21 added-4 removed
46 unmodified lines
47 return {}48 return LRUCache(size)495051def 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)585960def 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 lines
293 setattr(rv, key, value)294295 if cache_size is not missing:296 rv.cache = create_cache(cache_size)297 else:298 rv.cache = copy_cache(self.cache)299300 rv.extensions = {}301 for key, value in self.extensions.iteritems():302 rv.extensions[key] = value.bind(rv)
47 unmodified lines
350 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 e356357 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 lines
363 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 e373374 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 lines
608 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 lines
modified:jinja2/exceptions.py+26 added-13 removed
24 unmodified lines
25class TemplateSyntaxError(TemplateError):26 """Raised to tell the user that there is a problem with the template."""2728 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 = message3738 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]4445 # 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())5354 return u'\n'.join(lines)5556 def __str__(self):57 return unicode(self).encode('utf-8')585960class 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 of
24 unmodified lines
modified:jinja2/filters.py+18 added-10 removed
337 unmodified lines
338339 {{ 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 rv347348349def do_truncate(s, length=255, killwords=False, end='...'):350 """Return a truncated copy of the string. The length is specified
297 unmodified lines
648649 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)666667668FILTERS = {669 'attr': do_attr,
46 unmodified lines
modified:jinja2/loaders.py+5 added-4 removed
12 unmodified lines
13 from hashlib import sha114except ImportError:15 from sha import new as sha116from jinja2.exceptions import TemplateNotFound17from jinja2.utils import LRUCache17from jinja2.utils import LRUCache, open_if_exists181920def split_template_path(template):21 """Split a path into segments and perform a sanity check. If it detects
119 unmodified lines
141 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 lines
170 """171172 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 lines
modified:jinja2/runtime.py+4 added-4 removed
163 unmodified lines
164 self.name165 )166167168# register the context as mutable mapping if possible168# register the context as mapping if possible169try:170 from collections import MutableMapping171 MutableMapping.register(Context)170 from collections import Mapping171 Mapping.register(Context)172except ImportError:173 pass174175
232 unmodified lines
408 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \409 __int__ = __float__ = __complex__ = _fail_with_undefined_error410411 def __str__(self):412 return self.__unicode__().encode('utf-8')412 return unicode(self).encode('utf-8')413414 def __unicode__(self):415 return u''416
67 unmodified lines
modified:jinja2/utils.py+37 added
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12import sys13import errno14try:15 from thread import allocate_lock16except ImportError:17 from dummy_thread import allocate_lock
155 unmodified lines
173 if not silent:174 raise175176177def 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 raise186187188def pformat(obj, verbose=False):189 """Prettyprint an object. Either use the `pretty` library or the190 builtin `pprint`.191 """
467 unmodified lines
659except ImportError:660 pass661662663class Cycler(object):664 """A cycle helper for templates."""665666 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()671672 def reset(self):673 """Resets the cycle."""674 self.pos = 0675676 @property677 def current(self):678 """Returns the current item."""679 return self.items[self.pos]680681 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 rv686687688# we have to import it down here as the speedups module imports the689# markup type which is define above.690try:691 from jinja2._speedups import escape, soft_unicode
37 unmodified lines
modified:tests/test_debug.py+2 added-2 removed
29 unmodified lines
30test_syntax_error = '''31>>> tmpl = MODULE.env.get_template('syntaxerror.html')32Traceback (most recent call last):33 ...34TemplateSyntaxError: unknown tag 'endif'34 File "loaderres/templates/syntaxerror.html", line 4, in <module>35 File "loaderres/templates/syntaxerror.html", line 436 {% endif %}36TemplateSyntaxError: unknown tag 'endif' (syntaxerror.html, line 4)37'''
modified:tests/test_filters.py+2 added-2 removed
150 unmodified lines
151def 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')157158159def test_int(env):160 tmpl = env.from_string(INT)
171 unmodified lines
modified:tests/test_security.py+8 added-12 removed
9 unmodified lines
10from jinja2 import Environment11from jinja2.sandbox import SandboxedEnvironment, \12 ImmutableSandboxedEnvironment, unsafe13from jinja2 import Markup, escape14from jinja2.exceptions import SecurityError14from jinja2.exceptions import SecurityError, TemplateSyntaxError151617class PrivateStuff(object):18
42 unmodified lines
61SecurityError: access to attribute '__class__' of 'int' object is unsafe.62'''636465test_restricted = '''66>>> env = MODULE.SandboxedEnvironment()67>>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")68Traceback (most recent call last):69 ...70TemplateSyntaxError: expected token 'in', got '.' (line 1)71>>> env.from_string("{% for foo, bar.baz in seq %}...{% endfor %}")72Traceback (most recent call last):73 ...74TemplateSyntaxError: expected token 'in', got '.' (line 1)75'''65def 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 %}")717273test_immutable_environment = '''74>>> env = MODULE.ImmutableSandboxedEnvironment()
6 unmodified lines
81 ...82SecurityError: access to attribute 'clear' of 'dict' object is unsafe.83'''848586def 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 lines
modified:tests/test_various.py+13 added
7 unmodified lines
8"""9import gc10from py.test import raises11from jinja2 import escape12from jinja2.utils import Cycler13from jinja2.exceptions import TemplateSyntaxError141516UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''
67 unmodified lines
84 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() == '<>'888990def 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 == 1
modified:CHANGES+2 added
35 unmodified lines
3637- inclusions and imports "with context" forward all variables now, not only38 the initial context.3940- added a cycle helper called `cycle`.4142Version 2.043-----------44(codename jinjavitus, released on July 17th 2008)45
32 unmodified lines