Skip to content
Myr

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

6 files+40 added−47 removed

modified:docs/api.rst+8 added-6 removed
168 unmodified lines
169Loaders are responsible for loading templates from a resource such as the170file system. The environment will keep the compiled modules in memory like171Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in172size by default and templates are automatically reloaded.173All loaders are subclasses of :class:`BaseLoader`. If you want to create your174175own loader, subclass :class:`BaseLoader` and override `get_source`.176177.. autoclass:: jinja2.loaders.BaseLoader178 :members: get_source, load179180Here a list of the builtin loaders Jinja2 provides:181182.. autoclass:: jinja2.loaders.FileSystemLoader183184.. autoclass:: jinja2.loaders.PackageLoader185
4 unmodified lines
190.. autoclass:: jinja2.loaders.PrefixLoader191192.. autoclass:: jinja2.loaders.ChoiceLoader193186All loaders are subclasses of :class:`BaseLoader`. If you want to create your187own loader, subclass :class:`BaseLoader` and override `get_source`.194189.. autoclass:: jinja2.loaders.BaseLoader190 :members: get_source, load191192195Utilities196---------197198These helper functions and classes are useful if you add custom filters or
140 unmodified lines
modified:jinja2/filters.py+21 added-26 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12import math13import textwrap14from random import choice15from operator import itemgetter16from itertools import imap, groupby17from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode
76 unmodified lines
94 escaped:9596 .. sourcecode:: html+jinja9797 <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 lines
291 """292 return pformat(value, verbose=verbose)293294295@environmentfilter294def do_urlize(value, trim_url_limit=None, nofollow=False):296def do_urlize(environment, value, trim_url_limit=None, nofollow=False):297 """Converts URLs in plain text into clickable links.298299 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":302303 .. sourcecode:: jinja304303 {{ 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 rv312313314def do_indent(s, width=4, indentfirst=False):315 """Return a copy of the passed string, each line indented by
2 unmodified lines
318 you can pass additional parameters to the filter:319320 .. sourcecode:: jinja321317 {{ 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 lines
358 result.append(end)359 return u' '.join(result)360361357def do_wordwrap(s, pos=79, hard=False):362def 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)372371 # 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(' '))373378374def do_wordcount(s):375 """Count the words in that string."""376 return len(s.split())377
32 unmodified lines
410411 {{ "%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)418419420def do_trim(value):421 """Strip leading and trailing whitespace."""
243 unmodified lines
modified:jinja2/lexer.py+2 added-2 removed
135 unmodified lines
136 """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 False147148 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 True
421 unmodified lines
modified:jinja2/loaders.py+1 added-5 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~56 Jinja loader classes.78 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.118 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from os import path
242 unmodified lines
254255 >>> loader = ChoiceLoader([256 ... FileSystemLoader('/path/to/user/templates'),257 ... PackageLoader('myapplication')262 ])258 .. ])259260 This is useful if you want to allow users to override builtin templates261 from a different location.262 """
11 unmodified lines
modified:jinja2/parser.py+2 added-3 removed
150 unmodified lines
151 node.template = self.parse_expression()152 return node153154 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 lines
720 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 lines
modified:jinja2/utils.py+6 added-5 removed
34 unmodified lines
3536# 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''.join40try:41 def _test_gen_bug():42 raise TypeError(_test_gen_bug)43 yield None43 u''.join(_test_gen_bug())44 _concat(_test_gen_bug())45except 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, _error585960def contextfunction(f):
428 unmodified lines