Skip to content
Myr

improved filters

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 18c6ca0 · Browse files · 4 files+129 added−197 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+129 added−197 removed

  • other:+129 added−197 removed

4 files+129 added−197 removed

modified:jinja2/compiler.py+2 added
1003 unmodified lines
1004 self.write('f_%s(' % node.name)1005 func = self.environment.filters.get(node.name)1006 if getattr(func, 'contextfilter', False):1007 self.write('context, ')1008 elif getattr(func, 'environmentfilter', False):1009 self.write('environment, ')1010 if isinstance(node.node, nodes.Filter):1011 self.visit_Filter(node.node, frame, initial)1012 elif node.node is None:1013 self.write(initial)
43 unmodified lines
modified:jinja2/filters.py+116 added-197 removed
7 unmodified lines
8 :copyright: 2008 by Armin Ronacher, Christoph Hack.9 :license: BSD, see LICENSE for more details.10"""11import re12import math13from random import choice14try:15 from operator import itemgetter16except ImportError:17 itemgetter = lambda a: lambda b: b[a]18from urllib import urlencode, quote19from itertools import imap18from jinja2.utils import Markup, escape, pformat, urlize20from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode21from jinja2.runtime import Undefined222324
3 unmodified lines
28def contextfilter(f):29 """Decorator for marking context dependent filters. The current context30 argument will be passed as first argument.31 """32 if getattr(f, 'environmentfilter', False):33 raise TypeError('filter already marked as environment filter')34 f.contextfilter = True35 return f363734def do_replace(s, old, new, count=None):38def environmentfilter(f):39 """Decorator for marking evironment dependent filters. The environment40 used for the template is passed to the filter as first argument.41 """42 if getattr(f, 'contextfilter', False):43 raise TypeError('filter already marked as context filter')44 f.environmentfilter = True45 return f464748def do_replace(s, old, new, count=None):36 Return a copy of the value with all occurrences of a substring49 """Return a copy of the value with all occurrences of a substring50 replaced with a new one. The first argument is the substring51 that should be replaced, the second is the replacement string.52 If the optional third argument ``count`` is given, only the first53 ``count`` occurrences are replaced:
5 unmodified lines
5960 {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}61 -> d'oh, d'oh, aaargh62 """50 if not isinstance(old, basestring) or \51 not isinstance(new, basestring):52 raise FilterArgumentError('the replace filter requires '53 'string replacement arguments')63 if count is None:55 return s.replace(old, new)56 if not isinstance(count, (int, long)):57 raise FilterArgumentError('the count parameter of the '58 'replace filter requires '59 'an integer')64 count = -165 if hasattr(old, '__html__') or hasattr(new, '__html__') and \66 not hasattr(s, '__html__'):67 s = escape(s)68 else:69 s = soft_unicode(s)70 return s.replace(old, new, count)717273def do_upper(s):74 """Convert a value to uppercase."""65 return unicode(s).upper()75 return soft_unicode(s).upper()767778def do_lower(s):79 """Convert a value to lowercase."""70 return unicode(s).lower()80 return soft_unicode(s).lower()818273def do_escape(s, attribute=False):74 """75 XML escape ``&``, ``<``, and ``>`` in a string of data. If the76 optional parameter is `true` this filter will also convert77 ``"`` to ``&quot;``. This filter is just used if the environment78 was configured with disabled `auto_escape`.83def do_escape(s):84 """XML escape ``&``, ``<``, ``>``, and ``"`` in a string of data.8586 This method will have no effect it the value is already escaped.87 """82 return escape(unicode(s), attribute)88 return escape(s)899091def do_xmlattr(d, autospace=False):86 """87 Create an SGML/XML attribute string based on the items in a dict.92 """Create an SGML/XML attribute string based on the items in a dict.93 All values that are neither `none` nor `undefined` are automatically94 escaped:9596 .. sourcecode:: html+jinja
13 unmodified lines
110111 As you can see it automatically prepends a space in front of the item112 if the filter returned something. You can disable this by passing113 `false` as only argument to the filter.109110 *New in Jinja 1.1*114 """115 if not hasattr(d, 'iteritems'):116 raise TypeError('a dict is required')117 result = []
2 unmodified lines
120 result.append(u'%s="%s"' % (121 escape(env.to_unicode(key)),122 escape(env.to_unicode(value), True)123 ))121 rv = u' '.join(result)124 rv = u' '.join(125 u'%s="%s"' % (escape(key), escape(value))126 for key, value in d.iteritems()127 if value is not None and not isinstance(value, Undefined)128 )129 if autospace:130 rv = ' ' + rv124 return rv131 return Markup(rv)132133134def do_capitalize(s):128 """129 Capitalize a value. The first character will be uppercase, all others135 """Capitalize a value. The first character will be uppercase, all others136 lowercase.137 """132 return unicode(s).capitalize()138 return soft_unicode(s).capitalize()139140141def do_title(s):136 """137 Return a titlecased version of the value. I.e. words will start with142 """Return a titlecased version of the value. I.e. words will start with143 uppercase letters, all remaining characters are lowercase.144 """140 return unicode(s).title()145 return soft_unicode(s).title()146147148def do_dictsort(value, case_sensitive=False, by='key'):144 """145 Sort a dict and yield (key, value) pairs. Because python dicts are149 """ Sort a dict and yield (key, value) pairs. Because python dicts are150 unsorted you may want to use this function to order them by either151 key or value:152153 .. sourcecode:: jinja
14 unmodified lines
168 pos = 1169 else:170 raise FilterArgumentError('You can only sort by either '171 '"key" or "value"')168 def sort_func(value):172 def sort_func(item):173 value = item[pos]174 if isinstance(value, basestring):175 value = unicode(value)176 if not case_sensitive:177 value = value.lower()178 return value179175 items = value.items()176 items.sort(lambda a, b: cmp(sort_func(a[pos]), sort_func(b[pos])))177 return items180 return sorted(value.items(), key=sort_func)181182183def do_default(value, default_value=u'', boolean=False):181 """182 If the value is undefined it will return the passed default value,184 """If the value is undefined it will return the passed default value,185 otherwise the value of the variable:186187 .. sourcecode:: jinja188
13 unmodified lines
202 return value203204205def do_join(value, d=u''):204 """205 Return a string which is the concatenation of the strings in the206 """Return a string which is the concatenation of the strings in the207 sequence. The separator between elements is an empty string per208 default, you can define ith with the optional parameter:209210 .. sourcecode:: jinja
3 unmodified lines
214215 {{ [1, 2, 3]|join }}216 -> 123217 """217 return unicode(d).join(unicode(x) for x in value)218 # if the delimiter doesn't have an html representation we check219 # if any of the items has. If yes we do a coercion to Markup220 if not hasttr(d, '__html__'):221 value = list(value)222 do_escape = False223 for idx, item in enumerate(value):224 if hasattr(item, '__html__'):225 do_escape = True226 else:227 value[idx] = unicode(item)228 if do_escape:229 d = escape(d)230 else:231 d = unicode(d)232 return d.join(value)233234 # no html involved, to normal joining235 return soft_unicode(d).join(imap(soft_unicode, value))236237238def do_center(value, width=80):221 """222 Centers the value in a field of a given width.223 """239 """Centers the value in a field of a given width."""240 return unicode(value).center(width)241242227@contextfilter228def do_first(context, seq):229 """230 Return the frist item of a sequence.231 """243@environmentfilter244def do_first(environment, seq):245 """Return the frist item of a sequence."""246 try:247 return iter(seq).next()248 except StopIteration:235 return context.environment.undefined('seq|first',249 return environment.undefined('seq|first',250 extra='the sequence was empty')251252239@contextfilter240def do_last(context, seq):241 """242 Return the last item of a sequence.243 """253@environmentfilter254def do_last(environment, seq):255 """Return the last item of a sequence."""256 try:257 return iter(reversed(seq)).next()258 except StopIteration:247 return context.environment.undefined('seq|last',259 return environment.undefined('seq|last',260 extra='the sequence was empty')261262251@contextfilter252def do_random(context, seq):253 """254 Return a random item from the sequence.255 """263@environmentfilter264def do_random(environment, seq):265 """Return a random item from the sequence."""266 try:267 return choice(seq)268 except IndexError:259 return context.environment.undefined('seq|random',269 return environment.undefined('seq|random',270 extra='the sequence was empty')271272263def do_jsonencode(value):264 """265 JSON dump a variable. just works if simplejson is installed.266267 .. sourcecode:: jinja268269 {{ 'Hello World'|jsonencode }}270 -> "Hello World"271 """272 global simplejson273 try:274 simplejson275 except NameError:276 import simplejson277 return simplejson.dumps(value)278279273def do_filesizeformat(value):281 """282 Format the value like a 'human-readable' file size (i.e. 13 KB,274 """Format the value like a 'human-readable' file size (i.e. 13 KB,275 4.1 MB, 102 bytes, etc).276 """277 # fail silently278 try:
10 unmodified lines
289 return "%.1f GB" % (bytes / (1024 * 1024 * 1024))290291292def do_pprint(value, verbose=False):301 """302 Pretty print a variable. Useful for debugging.293 """Pretty print a variable. Useful for debugging.294295 With Jinja 1.2 onwards you can pass it a parameter. If this parameter296 is truthy the output will be more verbose (this requires `pretty`)297 """298 return pformat(value, verbose=verbose)299300301def do_urlize(value, trim_url_limit=None, nofollow=False):311 """312 Converts URLs in plain text into clickable links.302 """Converts URLs in plain text into clickable links.303304 If you pass the filter an additional integer it will shorten the urls305 to that number. Also a third argument exists that makes the urls306 "nofollow":
2 unmodified lines
309310 {{ mytext|urlize(40, True) }}311 links are shortened to 40 chars and defined with rel="nofollow"312 """323 return urlize(unicode(value), trim_url_limit, nofollow)313 return urlize(soft_unicode(value), trim_url_limit, nofollow)314315316def do_indent(s, width=4, indentfirst=False):317 """
10 unmodified lines
328 indent by two spaces and indent the first line too.329 """330 indention = ' ' * width331 if indentfirst:342 return u'\n'.join([indention + line for line in s.splitlines()])332 return u'\n'.join(indention + line for line in s.splitlines())333 return s.replace('\n', '\n' + indention)334335336def do_truncate(s, length=255, killwords=False, end='...'):
38 unmodified lines
375 """376 if len(s) < pos:377 return s378 if hard:389 return u'\n'.join([s[idx:idx + pos] for idx in390 xrange(0, len(s), pos)])379 return u'\n'.join(s[idx:idx + pos] for idx in380 xrange(0, len(s), pos))381382 # TODO: switch to wordwrap.wrap383 # code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061384 return reduce(lambda line, word, pos=pos: u'%s%s%s' %385 (line, u' \n'[(len(line)-line.rfind('\n') - 1 +386 len(word.split('\n', 1)[0]) >= pos)],387 word), s.split(' '))388389390def do_wordcount(s):399 """400 Count the words in that string.401 """402 return len([x for x in s.split() if x])391 """Count the words in that string."""392 return len(x for x in s.split() if x)393394405def do_textile(s):406 """407 Prase the string using textile.408409 requires the `PyTextile`_ library.410411 .. _PyTextile: http://dealmeida.net/projects/textile/412 """413 from textile import textile414 return textile(s.encode('utf-8')).decode('utf-8')415416417def do_markdown(s):418 """419 Parse the string using markdown.420421 requires the `Python-markdown`_ library.422423 .. _Python-markdown: http://www.freewisdom.org/projects/python-markdown/424 """425 from markdown import markdown426 return markdown(s.encode('utf-8')).decode('utf-8')427428429def do_rst(s):430 """431 Parse the string using the reStructuredText parser from the432 docutils package.433434 requires `docutils`_.435436 .. _docutils: http://docutils.sourceforge.net/437 """438 from docutils.core import publish_parts439 parts = publish_parts(source=s, writer_name='html4css1')440 return parts['fragment']441442395def do_int(value, default=0):444 """445 Convert the value into an integer. If the396 """Convert the value into an integer. If the397 conversion doesn't work it will return ``0``. You can398 override this default using the first parameter.399 """400 try:
5 unmodified lines
406 return default407408409def do_float(value, default=0.0):459 """460 Convert the value into a floating point number. If the410 """Convert the value into a floating point number. If the411 conversion doesn't work it will return ``0.0``. You can412 override this default using the first parameter.413 """414 try:
2 unmodified lines
417 return default418419420def do_string(value):471 """472 Convert the value into an string.473 """474 return unicode(value)421 """Convert the value into an string."""422 return soft_unicode(value)423424425def do_format(value, *args, **kwargs):426 """
6 unmodified lines
433 """434 if kwargs:435 kwargs.update(idx, arg in enumerate(args))436 args = kwargs489 return unicode(value) % args437 return soft_unicode(value) % args438439440def do_trim(value):493 """494 Strip leading and trailing whitespace.495 """496 return value.strip()441 """Strip leading and trailing whitespace."""442 return soft_unicode(value).strip()443444445def do_striptags(value):446 """Strip SGML/XML tags and replace adjacent whitespace by one space.447 """501 Strip SGML/XML tags and replace adjacent whitespace by one space.502503 *new in Jinja 1.1*504 """448 return ' '.join(_striptags_re.sub('', value).split())449450451def do_slice(value, slices, fill_with=None):509 """510 Slice an iterator and return a list of lists containing452 """Slice an iterator and return a list of lists containing453 those items. Useful if you want to create a div containing454 three div tags that represent columns:455456 .. sourcecode:: html+jinja
9 unmodified lines
466 </div>467468 If you pass it a second argument it's used to fill missing469 values on the last iteration.528529 *new in Jinja 1.1*470 """471 result = []472 seq = list(value)473 length = len(seq)
29 unmodified lines
503 {%- endfor %}504 </tr>505 {%- endfor %}506 </table>567568 *new in Jinja 1.1*507 """508 result = []509 tmp = []510 for item in value:
7 unmodified lines
518 result.append(tmp)519 return result520521584def do_round(precision=0, method='common'):585 """586 Round the number to a given precision. The first522def do_round(value, precision=0, method='common'):523 """Round the number to a given precision. The first524 parameter specifies the precision (default is ``0``), the525 second the rounding method:526527 - ``'common'`` rounds either up or down
7 unmodified lines
535 {{ 42.55|round }}536 -> 43537 {{ 42.55|round(1, 'floor') }}538 -> 42.5602603 *new in Jinja 1.1*539 """540 if not method in ('common', 'ceil', 'floor'):541 raise FilterArgumentError('method must be common, ceil or floor')542 if precision < 0:543 raise FilterArgumentError('precision must be a postive integer '544 'or zero.')610 def wrapped(env, context, value):611 if method == 'common':612 return round(value, precision)613 import math614 func = getattr(math, method)615 if precision:616 return func(value * 10 * precision) / (10 * precision)617 else:618 return func(value)545 if method == 'common':546 return round(value, precision)547 func = getattr(math, method)548 if precision:549 return func(value * 10 * precision) / (10 * precision)550 else:551 return func(value)619 return wrapped552553622def do_sort(reverse=False):623 """624 Sort a sequence. Per default it sorts ascending, if you pass it554def do_sort(value, reverse=False):555 """Sort a sequence. Per default it sorts ascending, if you pass it556 `True` as first argument it will reverse the sorting.626627 *new in Jinja 1.1*557 """629 def wrapped(env, context, value):630 return sorted(value, reverse=reverse)558 return sorted(value, reverse=reverse)631 return wrapped559560634def do_groupby(attribute):635 """636 Group a sequence of objects by a common attribute.561@environmentfilter562def do_groupby(environment, value, attribute):563 """Group a sequence of objects by a common attribute.564565 If you for example have a list of dicts or objects that represent persons566 with `gender`, `first_name` and `last_name` attributes and you want to567 group all users by genders you can do something like the following
12 unmodified lines
580581 As you can see the item we're grouping by is stored in the `grouper`582 attribute and the `list` contains all the objects that have this grouper583 in common.657658 *New in Jinja 1.2*584 """660 def wrapped(env, context, value):661 expr = lambda x: env.get_attribute(x, attribute)662 return sorted([{663 'grouper': a,664 'list': list(b)665 } for a, b in groupby(sorted(value, key=expr), expr)],666 key=itemgetter('grouper'))585 expr = lambda x: environment.subscribe(x, attribute)586 return sorted([{587 'grouper': a,588 'list': b589 } for a, b in groupby(sorted(value, key=expr), expr)],590 key=itemgetter('grouper'))667 return wrapped591592593FILTERS = {594 'replace': do_replace,
15 unmodified lines
610 'capitalize': do_capitalize,611 'first': do_first,612 'last': do_last,613 'random': do_random,691 'jsonencode': do_jsonencode,614 'filesizeformat': do_filesizeformat,615 'pprint': do_pprint,616 'indent': do_indent,617 'truncate': do_truncate,618 'wordwrap': do_wordwrap,619 'wordcount': do_wordcount,698 'textile': do_textile,699 'markdown': do_markdown,700 'rst': do_rst,620 'int': do_int,621 'float': do_float,622 'string': do_string,623 'urlize': do_urlize,
12 unmodified lines
modified:jinja2/nodes.py+2 added
417 unmodified lines
418 raise Impossible()419 if obj is None:420 obj = self.node.as_const()421 args = [x.as_const() for x in self.args]422 if getattr(filter, 'environmentfilter', False):423 args.insert(0, self.environment)424 kwargs = dict(x.as_const() for x in self.kwargs)425 if self.dyn_args is not None:426 try:427 args.extend(self.dyn_args.as_const())
160 unmodified lines
modified:jinja2/utils.py+9 added
24 unmodified lines
25 .replace('"', '&quot;')26 )272829def soft_unicode(s):30 """Make a string unicode if it isn't already. That way a markup31 string is not converted back to unicode.32 """33 if not isinstance(s, unicode):34 s = unicode(s)35 return s363738def pformat(obj, verbose=False):39 """40 Prettyprint an object. Either use the `pretty` library or the41 builtin `pprint`.
155 unmodified lines