From eec3138d28317e0ccd76640be6e6624675f3e78a Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Sat, 14 Apr 2007 14:50:45 +0200 Subject: [PATCH] [svn] implemented some of the builtin functions as filters (namely sum, abs and round). this fixes #238 --HG-- branch : trunk --- CHANGES | 4 ++- jinja/filters.py | 63 +++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/CHANGES b/CHANGES index ed38941..5f7a71c 100644 --- a/CHANGES +++ b/CHANGES @@ -37,7 +37,9 @@ Version 1.1 - fixed a bug that allowed users to override the special names `_`, `true` etc. -- added `batch` and `slice` filters +- added `batch` and `slice` filters for batching or slicing sequences + +- added `sum`, `abs` and `round` filters. This fixes #238 Version 1.0 diff --git a/jinja/filters.py b/jinja/filters.py index 089554c..e1d7d65 100644 --- a/jinja/filters.py +++ b/jinja/filters.py @@ -636,7 +636,10 @@ def do_slice(slices, fill_with=None): {%- endfor %} - *New in Jinja 1.1* + If you pass it a second argument it's used to fill missing + values on the last iteration. + + *new in Jinja 1.1* """ def wrapped(env, context, value): result = [] @@ -677,7 +680,7 @@ def do_batch(linecount, fill_with=None): {%- endfor %} - *New in Jinja 1.1* + *new in Jinja 1.1* """ def wrapped(env, context, value): result = [] @@ -695,6 +698,57 @@ def do_batch(linecount, fill_with=None): return wrapped +def do_sum(): + """ + Sum up the given sequence of numbers. + """ + def wrapped(env, context, value): + return sum(value) + return wrapped + + +def do_abs(): + """ + Return the absolute value of a number. + """ + def wrapped(env, context, value): + return abs(value) + return wrapped + + +def do_round(precision=0, method='common'): + """ + Round the number to a given precision. The first + parameter specifies the precision (default is ``0``), the + second the rounding method: + + - ``'common'`` rounds either up or down + - ``'ceil'`` always rounds up + - ``'floor'`` always rounds down + + If you don't specify a method ``'common'`` is used. + + .. sourcecode:: jinja + + {{ 42.55|round }} + -> 43 + {{ 42.55|round(1, 'floor') }} + -> 42.5 + """ + if not method in ('common', 'ceil', 'floor'): + raise FilterArgumentError('method must be common, ceil or floor') + if precision < 0: + raise FilterArgumentError('precision must be a postive integer ' + 'or zero.') + def wrapped(env, context, value): + if method == 'common': + return round(value, precision) + import math + func = getattr(math, method) + return func(value * 10 * precision) / (10 * precision) + return wrapped + + FILTERS = { 'replace': do_replace, 'upper': do_upper, @@ -734,5 +788,8 @@ FILTERS = { 'capture': do_capture, 'trim': do_trim, 'slice': do_slice, - 'batch': do_batch + 'batch': do_batch, + 'sum': do_sum, + 'abs': do_abs, + 'round': do_round } -- 2.26.2