updated filters: wordwraps uses the wordwrap module and urlize marks the result as HTML now if in autoescape mode
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 7ceced5 · Browse files · 6 files·+40 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+40 added−47 removed
- other:+40 added−47 removed
Provenance
- Commit
cda43df- Tree
20da40e- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
7ceced5
6 files changed+40 added−47 removed
modified:docs/api.rst+8 added-6 removed
168 unmodified lines169 Loaders are responsible for loading templates from a resource such as the170 file system. The environment will keep the compiled modules in memory like171 Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in172 size by default and templates are automatically reloaded.173+All loaders are subclasses of :class:`BaseLoader`. If you want to create your174 175+own loader, subclass :class:`BaseLoader` and override `get_source`.176+177+.. autoclass:: jinja2.loaders.BaseLoader178+ :members: get_source, load179+180+Here a list of the builtin loaders Jinja2 provides:181+182 .. autoclass:: jinja2.loaders.FileSystemLoader183 184 .. autoclass:: jinja2.loaders.PackageLoader185 4 unmodified lines190 .. autoclass:: jinja2.loaders.PrefixLoader191 192 .. autoclass:: jinja2.loaders.ChoiceLoader193 186-All loaders are subclasses of :class:`BaseLoader`. If you want to create your187-own loader, subclass :class:`BaseLoader` and override `get_source`.194 189-.. autoclass:: jinja2.loaders.BaseLoader190- :members: get_source, load191-192-195 Utilities196 ---------197 198 These helper functions and classes are useful if you add custom filters or140 unmodified linesmodified:jinja2/filters.py+21 added-26 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 import math13+import textwrap14 from random import choice15 from operator import itemgetter16 from itertools import imap, groupby17 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode76 unmodified lines94 escaped:95 96 .. sourcecode:: html+jinja97 97- <ul{{ {'class': 'my_list', 'missing': None,98+ <ul{{ {'class': 'my_list', 'missing': none,99 'id': 'list-%d'|format(variable)}|xmlattr }}>100 ...101 </ul>102 188 unmodified lines291 """292 return pformat(value, verbose=verbose)293 294 295+@environmentfilter294-def do_urlize(value, trim_url_limit=None, nofollow=False):296+def do_urlize(environment, value, trim_url_limit=None, nofollow=False):297 """Converts URLs in plain text into clickable links.298 299 If you pass the filter an additional integer it will shorten the urls300 to that number. Also a third argument exists that makes the urls301 "nofollow":302 303 .. sourcecode:: jinja304 303- {{ mytext|urlize(40, True) }}305+ {{ mytext|urlize(40, true) }}306 links are shortened to 40 chars and defined with rel="nofollow"307 """306- return urlize(soft_unicode(value), trim_url_limit, nofollow)308+ rv = urlize(soft_unicode(value), trim_url_limit, nofollow)309+ if environment.autoescape:310+ rv = Markup(rv)311+ return rv312 313 314 def do_indent(s, width=4, indentfirst=False):315 """Return a copy of the passed string, each line indented by2 unmodified lines318 you can pass additional parameters to the filter:319 320 .. sourcecode:: jinja321 317- {{ mytext|indent(2, True) }}322+ {{ mytext|indent(2, true) }}323 indent by two spaces and indent the first line too.324 """325 indention = ' ' * width326 if indentfirst:31 unmodified lines358 result.append(end)359 return u' '.join(result)360 361 357-def do_wordwrap(s, pos=79, hard=False):362+def do_wordwrap(s, width=79, break_long_words=True):363 """364 Return a copy of the string passed to the filter wrapped after360- ``79`` characters. You can override this default using the first361- parameter. If you set the second parameter to `true` Jinja will362- also split words apart (usually a bad idea because it makes363- reading hard).365+ ``79`` characters. You can override this default using the first366+ parameter. If you set the second parameter to `false` Jinja will not367+ split words apart if they are longer than `width`.368 """365- if len(s) < pos:366- return s367- if hard:368- return u'\n'.join(s[idx:idx + pos] for idx in369- xrange(0, len(s), pos))369+ return textwrap.wrap(s, width=width, expand_tabs=False,370+ replace_whitespace=False,371+ break_long_words=break_long_words)372 371- # TODO: switch to wordwrap.wrap372- # code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061373- return reduce(lambda line, word, pos=pos: u'%s%s%s' %374- (line, u' \n'[(len(line)-line.rfind('\n') - 1 +375- len(word.split('\n', 1)[0]) >= pos)],376- word), s.split(' '))373 378-374 def do_wordcount(s):375 """Count the words in that string."""376 return len(s.split())377 32 unmodified lines410 411 {{ "%s - %s"|format("Hello?", "Foo!") }}412 -> Hello? - Foo!413 """419- if kwargs:420- kwargs.update(idx, arg in enumerate(args))421- args = kwargs422- return soft_unicode(value) % args414+ if args and kwargs:415+ raise FilterArgumentError('can\'t handle positional and keyword '416+ 'arguments at the same time')417+ return soft_unicode(value) % (kwargs or args)418 419 420 def do_trim(value):421 """Strip leading and trailing whitespace."""243 unmodified linesmodified:jinja2/lexer.py+2 added-2 removed
135 unmodified lines136 """Test a token against a token expression. This can either be a137 token type or 'token_type:token_value'. This can only test against138 string values!139 """140- # here we do a regular string equality check as test_many is usually140+ # here we do a regular string equality check as test_any is usually141 # passed an iterable of not interned strings.142 if self.type == expr:143 return True144 elif ':' in expr:145 return expr.split(':', 1) == [self.type, self.value]146 return False147 148- def test_many(self, iterable):148+ def test_any(self, *iterable):149 """Test against multiple token expressions."""150 for expr in iterable:151 if self.test(expr):152 return True421 unmodified linesmodified:jinja2/loaders.py+1 added-5 removed
3 unmodified lines4 ~~~~~~~~~~~~~~5 6 Jinja loader classes.7 8- XXX: move caching from the loaders to environment.get_template and add9- environment overlays that allow to redefine escaping and other things but10- shared the globals and filter mappings.11-8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from os import path242 unmodified lines254 255 >>> loader = ChoiceLoader([256 ... FileSystemLoader('/path/to/user/templates'),257 ... PackageLoader('myapplication')262- ])258+ .. ])259 260 This is useful if you want to allow users to override builtin templates261 from a different location.262 """11 unmodified linesmodified:jinja2/parser.py+2 added-3 removed
150 unmodified lines151 node.template = self.parse_expression()152 return node153 154 def parse_import_context(self, node, default):155- if (self.stream.current.test('name:with') or156- self.stream.current.test('name:without')) and \155+ if self.stream.current.test_any('name:with', 'name:without') and \156 self.stream.look().test('name:context'):157 node.with_context = self.stream.next().value == 'with'158 self.stream.skip()159 else:560 unmodified lines720 elif token.type is 'block_begin':721 flush_data()722 self.stream.next()723 if end_tokens is not None and \725- self.stream.current.test_many(end_tokens):724+ self.stream.current.test_any(*end_tokens):725 return body726 body.append(self.parse_statement())727 self.stream.expect('block_end')728 else:10 unmodified linesmodified:jinja2/utils.py+6 added-5 removed
34 unmodified lines35 36 # concatenate a list of strings and convert them to unicode.37 # unfortunately there is a bug in python 2.4 and lower that causes38 # unicode.join trash the traceback.39+_concat = u''.join40 try:41 def _test_gen_bug():42 raise TypeError(_test_gen_bug)43 yield None43- u''.join(_test_gen_bug())44+ _concat(_test_gen_bug())45 except TypeError, _error:45- if _error.args and _error.args[0] is _test_gen_bug:46- concat = u''.join47- else:46+ if not _error.args or _error.args[0] is not _test_gen_bug:47 def concat(gen):48 try:50- return u''.join(list(gen))49+ return _concat(list(gen))50 except:51 # this hack is needed so that the current frame52 # does not show up in the traceback.53 exc_type, exc_value, tb = sys.exc_info()54 raise exc_type, exc_value, tb.tb_next55+ else:56+ concat = _concat57 del _test_gen_bug, _error58 59 60 def contextfunction(f):428 unmodified lines