Added support for map, select, reject, selectattr and rejectattr
Before adoption: this commit came in with the history the project adopted, so no landing records it.
filters. This supercedes #66
authored by Armin Ronacher · committed by Armin Ronacher · parent dc4b4cd · Browse files · 4 files·+286 added−1 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+286 added−1 removed
- other:+286 added−1 removed
Provenance
- Commit
8eed53c- Tree
67a24d4- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
dc4b4cd
4 files changed+286 added−1 removed
modified:jinja2/testsuite/filters.py+103 added
390 unmodified lines391 assert tmpl.render(o=((u"\u203d", 1),)) == "%E2%80%BD=1"392 assert tmpl.render(o={u"\u203d": 1}) == "%E2%80%BD=1"393 assert tmpl.render(o={0: 1}) == "0=1"394 395+ def test_simple_map(self):396+ env = Environment()397+ tmpl = env.from_string('{{ ["1", "2", "3"]|map("int")|sum }}')398+ self.assertEqual(tmpl.render(), '6')399 400+ def test_attribute_map(self):401+ class User(object):402+ def __init__(self, name):403+ self.name = name404+ env = Environment()405+ users = [406+ User('john'),407+ User('jane'),408+ User('mike'),409+ ]410+ tmpl = env.from_string('{{ users|map(attribute="name")|join("|") }}')411+ self.assertEqual(tmpl.render(users=users), 'john|jane|mike')412+413+ def test_empty_map(self):414+ env = Environment()415+ tmpl = env.from_string('{{ none|map("upper")|list }}')416+ self.assertEqual(tmpl.render(), '[]')417+418+ def test_simple_select(self):419+ env = Environment()420+ tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|select("odd")|join("|") }}')421+ self.assertEqual(tmpl.render(), '1|3|5')422+423+ def test_bool_select(self):424+ env = Environment()425+ tmpl = env.from_string('{{ [none, false, 0, 1, 2, 3, 4, 5]|select|join("|") }}')426+ self.assertEqual(tmpl.render(), '1|2|3|4|5')427+428+ def test_simple_reject(self):429+ env = Environment()430+ tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|reject("odd")|join("|") }}')431+ self.assertEqual(tmpl.render(), '2|4')432+433+ def test_bool_reject(self):434+ env = Environment()435+ tmpl = env.from_string('{{ [none, false, 0, 1, 2, 3, 4, 5]|reject|join("|") }}')436+ self.assertEqual(tmpl.render(), 'None|False|0')437+438+ def test_simple_select_attr(self):439+ class User(object):440+ def __init__(self, name, is_active):441+ self.name = name442+ self.is_active = is_active443+ env = Environment()444+ users = [445+ User('john', True),446+ User('jane', True),447+ User('mike', False),448+ ]449+ tmpl = env.from_string('{{ users|selectattr("is_active")|'450+ 'map(attribute="name")|join("|") }}')451+ self.assertEqual(tmpl.render(users=users), 'john|jane')452+453+ def test_simple_reject_attr(self):454+ class User(object):455+ def __init__(self, name, is_active):456+ self.name = name457+ self.is_active = is_active458+ env = Environment()459+ users = [460+ User('john', True),461+ User('jane', True),462+ User('mike', False),463+ ]464+ tmpl = env.from_string('{{ users|rejectattr("is_active")|'465+ 'map(attribute="name")|join("|") }}')466+ self.assertEqual(tmpl.render(users=users), 'mike')467+468+ def test_func_select_attr(self):469+ class User(object):470+ def __init__(self, id, name):471+ self.id = id472+ self.name = name473+ env = Environment()474+ users = [475+ User(1, 'john'),476+ User(2, 'jane'),477+ User(3, 'mike'),478+ ]479+ tmpl = env.from_string('{{ users|selectattr("id", "odd")|'480+ 'map(attribute="name")|join("|") }}')481+ self.assertEqual(tmpl.render(users=users), 'john|mike')482+483+ def test_func_reject_attr(self):484+ class User(object):485+ def __init__(self, id, name):486+ self.id = id487+ self.name = name488+ env = Environment()489+ users = [490+ User(1, 'john'),491+ User(2, 'jane'),492+ User(3, 'mike'),493+ ]494+ tmpl = env.from_string('{{ users|rejectattr("id", "odd")|'495+ 'map(attribute="name")|join("|") }}')496+ self.assertEqual(tmpl.render(users=users), 'jane')497+498+499 def suite():500 suite = unittest.TestSuite()501 suite.addTest(unittest.makeSuite(FilterTestCase))502 return suitemodified:jinja2/environment.py+38 added-1 removed
17 unmodified lines18 DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \19 KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS20 from jinja2.lexer import get_lexer, TokenStream21 from jinja2.parser import Parser22+from jinja2.nodes import EvalContext23 from jinja2.optimizer import optimize24 from jinja2.compiler import generate25 from jinja2.runtime import Undefined, new_context26 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \26- TemplatesNotFound27+ TemplatesNotFound, TemplateRuntimeError28 from jinja2.utils import import_string, LRUCache, Markup, missing, \29 concat, consume, internalcode, _encode_filename30 import six31 from functools import reduce368 unmodified lines400 return obj[attribute]401 except (TypeError, LookupError, AttributeError):402 return self.undefined(obj=obj, name=attribute)403 404+ def call_filter(self, name, value, args=None, kwargs=None,405+ context=None, eval_ctx=None):406+ """Invokes a filter on a value the same way the compiler does it.407+408+ .. versionadded:: 2.7409+ """410+ func = self.filters.get(name)411+ if func is None:412+ raise TemplateRuntimeError('no filter named %r' % name)413+ args = list(args or ())414+ if getattr(func, 'contextfilter', False):415+ if context is None:416+ raise TemplateRuntimeError('Attempted to invoke context '417+ 'filter without context')418+ args.insert(0, context)419+ elif getattr(func, 'evalcontextfilter', False):420+ if eval_ctx is None:421+ if context is not None:422+ eval_ctx = context.eval_ctx423+ else:424+ eval_ctx = EvalContext(self)425+ args.insert(0, eval_ctx)426+ elif getattr(func, 'environmentfilter', False):427+ args.insert(0, self)428+ return func(value, *args, **(kwargs or {}))429+430+ def call_test(self, name, value, args=None, kwargs=None):431+ """Invokes a test on a value the same way the compiler does it.432+433+ .. versionadded:: 2.7434+ """435+ func = self.tests.get(name)436+ if func is None:437+ raise TemplateRuntimeError('no test named %r' % name)438+ return func(value, *(args or ()), **(kwargs or {}))439+440 @internalcode441 def parse(self, source, name=None, filename=None):442 """Parse the sourcecode and return the abstract syntax tree. This443 tree of nodes is used by the compiler to convert the template into742 unmodified linesmodified:jinja2/filters.py+143 added
788 unmodified lines789 return value790 return environment.undefined(obj=obj, name=name)791 792 793+@contextfilter794+def do_map(*args, **kwargs):795+ """Applies a filter on a sequence of objects or looks up an attribute.796+ This is useful when dealing with lists of objects but you are really797+ only interested in a certain value of it.798+799+ The basic usage is mapping on an attribute. Imagine you have a list800+ of users but you are only interested in a list of usernames:801+802+ .. sourcecode:: jinja803+804+ Users on this page: {{ users|map(attribute='username')|join(', ') }}805+806+ Alternatively you can let it invoke a filter by passing the name of the807+ filter and the arguments afterwards. A good example would be applying a808+ text conversion filter on a sequence:809+810+ .. sourcecode:: jinja811+812+ Users on this page: {{ titles|map('lower')|join(', ') }}813+814+ .. versionadded:: 2.7815+ """816+ context = args[0]817+ seq = args[1]818+819+ if len(args) == 2 and 'attribute' in kwargs:820+ attribute = kwargs.pop('attribute')821+ if kwargs:822+ raise FilterArgumentError('Unexpected keyword argument %r' %823+ six.advance_iterator(iter(kwargs)))824+ func = make_attrgetter(context.environment, attribute)825+ else:826+ try:827+ name = args[2]828+ args = args[3:]829+ except LookupError:830+ raise FilterArgumentError('map requires a filter argument')831+ func = lambda item: context.environment.call_filter(832+ name, item, args, kwargs, context=context)833+834+ if seq:835+ for item in seq:836+ yield func(item)837+838+839+@contextfilter840+def do_select(*args, **kwargs):841+ """Filters a sequence of objects by appying a test to either the object842+ or the attribute and only selecting the ones with the test succeeding.843+844+ Example usage:845+846+ .. sourcecode:: jinja847+848+ {{ numbers|select("odd") }}849+850+ .. versionadded:: 2.7851+ """852+ return _select_or_reject(args, kwargs, lambda x: x, False)853+854+855+@contextfilter856+def do_reject(*args, **kwargs):857+ """Filters a sequence of objects by appying a test to either the object858+ or the attribute and rejecting the ones with the test succeeding.859+860+ Example usage:861+862+ .. sourcecode:: jinja863+864+ {{ numbers|reject("odd") }}865+866+ .. versionadded:: 2.7867+ """868+ return _select_or_reject(args, kwargs, lambda x: not x, False)869+870+871+@contextfilter872+def do_selectattr(*args, **kwargs):873+ """Filters a sequence of objects by appying a test to either the object874+ or the attribute and only selecting the ones with the test succeeding.875+876+ Example usage:877+878+ .. sourcecode:: jinja879+880+ {{ users|selectattr("is_active") }}881+ {{ users|selectattr("email", "none") }}882+883+ .. versionadded:: 2.7884+ """885+ return _select_or_reject(args, kwargs, lambda x: x, True)886+887+888+@contextfilter889+def do_rejectattr(*args, **kwargs):890+ """Filters a sequence of objects by appying a test to either the object891+ or the attribute and rejecting the ones with the test succeeding.892+893+ .. sourcecode:: jinja894+895+ {{ users|rejectattr("is_active") }}896+ {{ users|rejectattr("email", "none") }}897+898+ .. versionadded:: 2.7899+ """900+ return _select_or_reject(args, kwargs, lambda x: not x, True)901+902+903+def _select_or_reject(args, kwargs, modfunc, lookup_attr):904+ context = args[0]905+ seq = args[1]906+ if lookup_attr:907+ try:908+ attr = args[2]909+ except LookupError:910+ raise FilterArgumentError('Missing parameter for attribute name')911+ transfunc = make_attrgetter(context.environment, attr)912+ off = 1913+ else:914+ off = 0915+ transfunc = lambda x: x916+917+ try:918+ name = args[2 + off]919+ args = args[3 + off:]920+ func = lambda item: context.environment.call_test(921+ name, item, args, kwargs)922+ except LookupError:923+ func = bool924+925+ if seq:926+ for item in seq:927+ if modfunc(func(transfunc(item))):928+ yield item929+930+931 FILTERS = {932 'attr': do_attr,933 'replace': do_replace,934 'upper': do_upper,16 unmodified lines951 'title': do_title,952 'capitalize': do_capitalize,953 'first': do_first,954 'last': do_last,955+ 'map': do_map,956 'random': do_random,957+ 'reject': do_reject,958+ 'rejectattr': do_rejectattr,959 'filesizeformat': do_filesizeformat,960 'pprint': do_pprint,961 'truncate': do_truncate,962 'wordwrap': do_wordwrap,5 unmodified lines968 'urlize': do_urlize,969 'format': do_format,970 'trim': do_trim,971 'striptags': do_striptags,972+ 'select': do_select,973+ 'selectattr': do_selectattr,974 'slice': do_slice,975 'batch': do_batch,976 'sum': do_sum,977 'abs': abs,6 unmodified linesmodified:CHANGES+2 added
24 unmodified lines25 - Added support for ignoring memcache errors silently.26 - Added support for keeping the trailing newline in templates.27 - Added finer grained support for stripping whitespace on the left side28 of blocks.29+- Added `map`, `select`, `reject`, `selectattr` and `rejectattr`30+ filters.31 32 Version 2.633 -----------34 (codename Convolution, released on July 24th 2011)263 unmodified lines