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
Provenance
- Commit
9a027f4- Tree
cbbbfe2- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
18c6ca0
4 files changed+129 added−197 removed
modified:jinja2/compiler.py+2 added
1003 unmodified lines1004 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 linesmodified:jinja2/filters.py+116 added-197 removed
7 unmodified lines8 :copyright: 2008 by Armin Ronacher, Christoph Hack.9 :license: BSD, see LICENSE for more details.10 """11 import re12+import math13 from random import choice14 try:15 from operator import itemgetter16 except ImportError:17 itemgetter = lambda a: lambda b: b[a]18 from urllib import urlencode, quote19+from itertools import imap18-from jinja2.utils import Markup, escape, pformat, urlize20+from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode21 from jinja2.runtime import Undefined22 23 24 3 unmodified lines28 def 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 f36 37 34-def do_replace(s, old, new, count=None):38+def 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 f46+47+48+def 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 lines59 60 {{ "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)71 72 73 def do_upper(s):74 """Convert a value to uppercase."""65- return unicode(s).upper()75+ return soft_unicode(s).upper()76 77 78 def do_lower(s):79 """Convert a value to lowercase."""70- return unicode(s).lower()80+ return soft_unicode(s).lower()81 82 73-def 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 ``"``. This filter is just used if the environment78- was configured with disabled `auto_escape`.83+def do_escape(s):84+ """XML escape ``&``, ``<``, ``>``, and ``"`` in a string of data.85 86 This method will have no effect it the value is already escaped.87 """82- return escape(unicode(s), attribute)88+ return escape(s)89 90 91 def 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:95 96 .. sourcecode:: html+jinja13 unmodified lines110 111 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.109-110- *New in Jinja 1.1*114 """115 if not hasattr(d, 'iteritems'):116 raise TypeError('a dict is required')117 result = []2 unmodified lines120 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)132 133 134 def 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()139 140 141 def 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()146 147 148 def 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:152 153 .. sourcecode:: jinja14 unmodified lines168 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 value179 175- 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)181 182 183 def 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:186 187 .. sourcecode:: jinja188 13 unmodified lines202 return value203 204 205 def 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:209 210 .. sourcecode:: jinja3 unmodified lines214 215 {{ [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)233 234+ # no html involved, to normal joining235+ return soft_unicode(d).join(imap(soft_unicode, value))236 237+238 def 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)241 242 227-@contextfilter228-def do_first(context, seq):229- """230- Return the frist item of a sequence.231- """243+@environmentfilter244+def 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')251 252 239-@contextfilter240-def do_last(context, seq):241- """242- Return the last item of a sequence.243- """253+@environmentfilter254+def 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')261 262 251-@contextfilter252-def do_random(context, seq):253- """254- Return a random item from the sequence.255- """263+@environmentfilter264+def 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')271 272 263-def do_jsonencode(value):264- """265- JSON dump a variable. just works if simplejson is installed.266-267- .. sourcecode:: jinja268-269- {{ 'Hello World'|jsonencode }}270- -> "Hello World"271- """272- global simplejson273- try:274- simplejson275- except NameError:276- import simplejson277- return simplejson.dumps(value)278-279-273 def 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 lines289 return "%.1f GB" % (bytes / (1024 * 1024 * 1024))290 291 292 def do_pprint(value, verbose=False):301- """302- Pretty print a variable. Useful for debugging.293+ """Pretty print a variable. Useful for debugging.294 295 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)299 300 301 def 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.303 304 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 lines309 310 {{ 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)314 315 316 def do_indent(s, width=4, indentfirst=False):317 """10 unmodified lines328 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)334 335 336 def do_truncate(s, length=255, killwords=False, end='...'):38 unmodified lines375 """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))381+382+ # 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(' '))388 389 390 def 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)393 394 405-def do_textile(s):406- """407- Prase the string using textile.408-409- requires the `PyTextile`_ library.410-411- .. _PyTextile: http://dealmeida.net/projects/textile/412- """413- from textile import textile414- return textile(s.encode('utf-8')).decode('utf-8')415-416-417-def do_markdown(s):418- """419- Parse the string using markdown.420-421- requires the `Python-markdown`_ library.422-423- .. _Python-markdown: http://www.freewisdom.org/projects/python-markdown/424- """425- from markdown import markdown426- return markdown(s.encode('utf-8')).decode('utf-8')427-428-429-def do_rst(s):430- """431- Parse the string using the reStructuredText parser from the432- docutils package.433-434- requires `docutils`_.435-436- .. _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']441-442-395 def 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 lines406 return default407 408 409 def 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 lines417 return default418 419 420 def 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)423 424 425 def do_format(value, *args, **kwargs):426 """6 unmodified lines433 """434 if kwargs:435 kwargs.update(idx, arg in enumerate(args))436 args = kwargs489- return unicode(value) % args437+ return soft_unicode(value) % args438 439 440 def 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()443 444 445 def 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.502-503- *new in Jinja 1.1*504- """448 return ' '.join(_striptags_re.sub('', value).split())449 450 451 def 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:455 456 .. sourcecode:: html+jinja9 unmodified lines466 </div>467 468 If you pass it a second argument it's used to fill missing469 values on the last iteration.528-529- *new in Jinja 1.1*470 """471 result = []472 seq = list(value)473 length = len(seq)29 unmodified lines503 {%- endfor %}504 </tr>505 {%- endfor %}506 </table>567-568- *new in Jinja 1.1*507 """508 result = []509 tmp = []510 for item in value:7 unmodified lines518 result.append(tmp)519 return result520 521 584-def do_round(precision=0, method='common'):585- """586- Round the number to a given precision. The first522+def 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:526 527 - ``'common'`` rounds either up or down7 unmodified lines535 {{ 42.55|round }}536 -> 43537 {{ 42.55|round(1, 'floor') }}538 -> 42.5602-603- *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 wrapped552 553 622-def do_sort(reverse=False):623- """624- Sort a sequence. Per default it sorts ascending, if you pass it554+def 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.626-627- *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 wrapped559 560 634-def do_groupby(attribute):635- """636- Group a sequence of objects by a common attribute.561+@environmentfilter562+def do_groupby(environment, value, attribute):563+ """Group a sequence of objects by a common attribute.564 565 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 following12 unmodified lines580 581 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.657-658- *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 wrapped591 592 593 FILTERS = {594 'replace': do_replace,15 unmodified lines610 '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 linesmodified:jinja2/nodes.py+2 added
417 unmodified lines418 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 linesmodified:jinja2/utils.py+9 added
24 unmodified lines25 .replace('"', '"')26 )27 28 29+def 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 s36+37+38 def pformat(obj, verbose=False):39 """40 Prettyprint an object. Either use the `pretty` library or the41 builtin `pprint`.155 unmodified lines