Skip to content
Myr

[svn] FILTERS!!111!!!111oneoneone

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 2d53a86 · Browse files · 4 files+343 added−6 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+343 added−6 removed

  • other:+343 added−6 removed

4 files+343 added−6 removed

modified:jinja/exceptions.py+9 added
27 unmodified lines
28 def __init__(self, message):29 KeyError.__init__(self, message)303132class FilterArgumentError(TypeError, TemplateError):33 """34 An argument passed to the filter was invalid.35 """3637 def __init__(self, message):38 TypeError.__init__(self, message)394041class TestNotFound(KeyError, TemplateError):42 """43 Raised if a test does not exist.44 """
29 unmodified lines
modified:jinja/filters.py+267 added-2 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from random import choice12from urllib import urlencode, quote13from jinja.utils import escape13from jinja.utils import escape, urlize14from jinja.datastructure import Undefined15from jinja.exceptions import FilterArgumentError161718try:19 _reversed = reversed
45 unmodified lines
6566 {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}67 -> d'oh, d'oh, aaargh68 """69 if not isinstance(old, basestring) or \70 not isinstance(new, basestring):71 raise FilterArgumentException('the replace filter requires '72 'string replacement arguments')73 elif not isinstance(count, (int, long)):74 raise FilterArgumentException('the count parameter of the '75 'replace filter requires '76 'an integer')77 if count is None:78 return s.replace(old, new)79 return s.replace(old, new, count)80do_replace = stringfilter(do_replace)
55 unmodified lines
136 return s.title()137do_title = stringfilter(do_title)138139140def do_dictsort(case_sensitive=False, by='key'):141 """142 Sort a dict and yield (key, value) pairs. Because python dicts are143 unsorted you may want to use this function to order them by either144 key or value:145146 .. sourcecode:: jinja147148 {% for item in mydict|dictsort %}149 sort the dict by key, case insensitive150151 {% for item in mydict|dicsort(true) %}152 sort the dict by key, case sensitive153154 {% for item in mydict|dictsort(false, 'value') %}155 sort the dict by key, case insensitive, sorted156 normally and ordered by value.157 """158 if by == 'key':159 pos = 0160 elif by == 'value':161 pos = 1162 else:163 raise FilterArgumentError('You can only sort by either '164 '"key" or "value"')165 def sort_func(value, env):166 if isinstance(value, basestring):167 value = env.to_unicode(value)168 if not case_sensitive:169 value = value.lower()170 return value171172 def wrapped(env, context, value):173 items = value.items()174 items.sort(lambda a, b: cmp(sort_func(a[pos], env),175 sort_func(b[pos], env)))176 return items177 return wrapped178179180def do_default(default_value=u'', boolean=False):181 """182 If the value is undefined it will return the passed default value,183 otherwise the value of the variable:
158 unmodified lines
342 import simplejson343 return lambda e, c, v: simplejson.dumps(v)344345346def do_filesizeformat():347 """348 Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102349 bytes, etc).350 """351 def wrapped(env, context, value):352 # fail silently353 try:354 bytes = float(value)355 except TypeError:356 bytes = 0357358 if bytes < 1024:359 return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')360 elif bytes < 1024 * 1024:361 return "%.1f KB" % (bytes / 1024)362 elif bytes < 1024 * 1024 * 1024:363 return "%.1f MB" % (bytes / (1024 * 1024))364 return "%.1f GB" % (bytes / (1024 * 1024 * 1024))365 return wrapped366367368def do_pprint():369 """370 Pretty print a variable. Useful for debugging.371 """372 def wrapped(env, context, value):373 from pprint import pformat374 return pformat(value)375 return wrapped376377378def do_urlize(value, trim_url_limit=None, nofollow=False):379 """380 Converts URLs in plain text into clickable links.381382 If you pass the filter an additional integer it will shorten the urls383 to that number. Also a third argument exists that makes the urls384 "nofollow":385386 .. sourcecode:: jinja387388 {{ mytext|urlize(40, True) }}389 links are shortened to 40 chars and defined with rel="nofollow"390 """391 return urlize(value, trim_url_limit, nofollow)392do_urlize = stringfilter(do_urlize)393394395def do_indent(s, width=4, indentfirst=False):396 """397 {{ s|indent[ width[ indentfirst[ usetab]]] }}398399 Return a copy of the passed string, each line indented by400 4 spaces. The first line is not indented. If you want to401 change the number of spaces or indent the first line too402 you can pass additional parameters to the filter:403404 .. sourcecode:: jinja405406 {{ mytext|indent(2, True) }}407 indent by two spaces and indent the first line too.408 """409 indention = ' ' * width410 if indentfirst:411 return u'\n'.join([indention + line for line in s.splitlines()])412 return s.replace('\n', '\n' + indention)413do_indent = stringfilter(do_indent)414415416def do_truncate(s, length=255, killwords=False, end='...'):417 """418 {{ s|truncate[ length[ killwords[ end]]] }}419420 Return a truncated copy of the string. The length is specified421 with the first parameter which defaults to ``255``. If the second422 parameter is ``true`` the filter will cut the text at length. Otherwise423 it will try to save the last word. If the text was in fact424 truncated it will append an ellipsis sign (``"..."``). If you want a425 different ellipsis sign than ``"..."`` you can specify it using the426 third parameter.427428 .. sourcecode jinja::429430 {{ mytext|truncate(300, false, '&raquo;') }}431 truncate mytext to 300 chars, don't split up words, use a432 right pointing double arrow as ellipsis sign.433 """434 if len(s) <= length:435 return s436 elif killwords:437 return s[:length] + end438 words = s.split(' ')439 result = []440 m = 0441 for word in words:442 m += len(word) + 1443 if m > length:444 break445 result.append(word)446 result.append(end)447 return u' '.join(result)448do_truncate = stringfilter(do_truncate)449450451def do_wordwrap(s, pos=79, hard=False):452 """453 Return a copy of the string passed to the filter wrapped after454 ``79`` characters. You can override this default using the first455 parameter. If you set the second parameter to `true` Jinja will456 also split words apart (usually a bad idea because it makes457 reading hard).458 """459 if len(s) < pos:460 return s461 if hard:462 return u'\n'.join([s[idx:idx + pos] for idx in463 xrange(0, len(s), pos)])464 # code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061465 return reduce(lambda line, word, pos=pos: u'%s%s%s' %466 (line, u' \n'[(len(line)-line.rfind('\n') - 1 +467 len(word.split('\n', 1)[0]) >= pos)],468 word), s.split(' '))469do_wordwrap = stringfilter(do_wordwrap)470471472def do_wordcount(s):473 """474 Count the words in that string.475 """476 return len([x for x in s.split() if x])477do_wordcount = stringfilter(do_wordcount)478479480def do_textile(s):481 """482 Prase the string using textile.483484 requires the `PyTextile`_ library.485486 .. _PyTextile: http://dealmeida.net/projects/textile/487 """488 from textile import textile489 return textile(s)490do_textile = stringfilter(do_textile)491492493def do_markdown(s):494 """495 Parse the string using markdown.496497 requires the `Python-markdown`_ library.498499 .. _Python-markdown: http://www.freewisdom.org/projects/python-markdown/500 """501 from markdown import markdown502 return markdown(s)503do_markdown = stringfilter(do_markdown)504505506def do_rst(s):507 """508 Parse the string using the reStructuredText parser from the509 docutils package.510511 requires `docutils`_.512513 .. _docutils: from http://docutils.sourceforge.net/514 """515 try:516 from docutils.core import publish_parts517 parts = publish_parts(source=s, writer_name='html4css1')518 return parts['fragment']519 except:520 return s521do_rst = stringfilter(do_rst)522523524def do_int():525 """526 Convert the value into an integer.527 """528 def wrapped(env, context, value):529 return int(value)530 return wrapped531532533def do_float():534 """535 Convert the value into a floating point number.536 """537 def wrapped(env, context, value):538 return float(value)539 return wrapped540541542def do_string():543 """544 Convert the value into an string.545 """546 return lambda e, c, v: e.to_unicode(v)547548549FILTERS = {550 'replace': do_replace,551 'upper': do_upper,552 'lower': do_lower,
4 unmodified lines
557 'title': do_title,558 'default': do_default,559 'join': do_join,560 'count': do_count,561 'dictsort': do_dictsort,562 'length': do_count,563 'reverse': do_reverse,564 'center': do_center,565 'title': do_title,
1 unmodified line
567 'first': do_first,568 'last': do_last,569 'random': do_random,570 'urlencode': do_urlencode,318 'jsonencode': do_jsonencode571 'jsonencode': do_jsonencode,572 'filesizeformat': do_filesizeformat,573 'pprint': do_pprint,574 'indent': do_indent,575 'truncate': do_truncate,576 'wordwrap': do_wordwrap,577 'wordcount': do_wordcount,578 'textile': do_textile,579 'markdown': do_markdown,580 'rst': do_rst,581 'int': do_int,582 'float': do_float,583 'string': do_string584}
modified:jinja/utils.py+64 added-2 removed
3 unmodified lines
4 ~~~~~~~~~~~56 Utility functions.78 **license information**: some of the regular expressions and9 the ``urlize`` function were taken from the django framework.108 :copyright: 2007 by Armin Ronacher.11 :copyright: 2007 by Armin Ronacher, Lawrence Journal-World.12 :license: BSD, see LICENSE for more details.13"""14import re15import sys16import string17from types import MethodType, FunctionType18from jinja.nodes import Trans19from jinja.datastructure import Markup20
15 unmodified lines
36 re.compile('(&|<|>|")'),37 re.compile('(&|<|>)')38)3940_integer_re = re.compile('^(\d+)$')4142_word_split_re = re.compile(r'(\s+)')4344_punctuation_re = re.compile(45 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (46 '|'.join([re.escape(p) for p in ('(', '<', '&lt;')]),47 '|'.join([re.escape(p) for p in ('.', ',', ')', '>', '\n', '&gt;')])48 )49)5051_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')525354def escape(x, attribute=False):55 """56 Escape an object x.57 """58 return Markup(_escape_res[not attribute].sub(lambda m:59 _escape_pairs[m.group()], x))606162def urlize(text, trim_url_limit=None, nofollow=False):63 """64 Converts any URLs in text into clickable links. Works on http://,65 https:// and www. links. Links can have trailing punctuation (periods,66 commas, close-parens) and leading punctuation (opening parens) and67 it'll still do the right thing.6869 If trim_url_limit is not None, the URLs in link text will be limited70 to trim_url_limit characters.7172 If nofollow is True, the URLs in link text will get a rel="nofollow"73 attribute.74 """75 trim_url = lambda x, limit=trim_url_limit: limit is not None \76 and (x[:limit] + (len(x) >=limit and '...'77 or '')) or x78 words = _word_split_re.split(text)79 nofollow_attr = nofollow and ' rel="nofollow"' or ''80 for i, word in enumerate(words):81 match = _punctuation_re.match(word)82 if match:83 lead, middle, trail = match.groups()84 if middle.startswith('www.') or (85 '@' not in middle and86 not middle.startswith('http://') and87 len(middle) > 0 and 88 middle[0] in string.letters + string.digits and (89 middle.endswith('.org') or90 middle.endswith('.net') or91 middle.endswith('.com')92 )):93 middle = '<a href="http://%s"%s>%s</a>' % (middle,94 nofollow_attr, trim_url(middle))95 if middle.startswith('http://') or \96 middle.startswith('https://'):97 middle = '<a href="%s"%s>%s</a>' % (middle,98 nofollow_attr, trim_url(middle))99 if '@' in middle and not middle.startswith('www.') and \100 not ':' in middle and _simple_email_re.match(middle):101 middle = '<a href="mailto:%s">%s</a>' % (middle, middle)102 if lead + middle + trail != word:103 words[i] = lead + middle + trail104 return u''.join(words)105106107def find_translations(environment, source):108 """109 Find all translatable strings in a template and yield110 them as (lineno, singular, plural) tuples. If a plural
48 unmodified lines
159 """160 Raise an exception "in a template". Return a traceback161 object.162 """101 # some traceback systems allow to skip blocks163 # some traceback systems allow to skip frames164 __traceback_hide__ = True165166 offset = '\n' * (lineno - 1)167 code = compile(offset + 'raise __exception_to_raise__', filename, 'exec')
177 unmodified lines
modified:setup.py+3 added-2 removed
12 unmodified lines
13 url = 'http://jinja.pocoo.org/',14 license = 'BSD',15 author = 'Armin Ronacher',16 author_email = 'armin.ronacher@active-4.com',17 description = 'A small but fast and easy to use stand-alone template engine written in pure python.',17 description = 'A small but fast and easy to use stand-alone template '18 'engine written in pure python.',19 zip_safe = True,20 classifiers = [21 'Development Status :: 5 - Production/Stable',22 'Environment :: Web Environment',
5 unmodified lines
28 'Topic :: Software Development :: Libraries :: Python Modules',29 'Topic :: Text Processing :: Markup :: HTML'30 ],31 keywords = ['python.templating.engines'],31 packages = ['jinja'],32 packages = ['jinja', 'jinja.translators'],33 extras_require = {'plugin': ['setuptools>=0.6a2']},34 entry_points='''35 [python.templating.engines]36 jinja = jinja.bakerplugin:JinjaPlugin[plugin]
2 unmodified lines