Permalink
Browse files

join now also accepts parameters

  • Loading branch information...
1 parent a8d2556 commit 3383e1ca375290d2cd248c11171ff7e5a2b92a4d @mitsuhiko mitsuhiko committed Jan 24, 2011
Showing with 24 additions and 2 deletions.
  1. +3 −0 CHANGES
  2. +13 −1 jinja2/filters.py
  3. +1 −0 jinja2/nodes.py
  4. +0 −1 jinja2/runtime.py
  5. +7 −0 jinja2/testsuite/filters.py
View
@@ -29,6 +29,9 @@ Version 2.6
optional starting index which defaultes to zero. This now became the
second argument to the function because it's rarely used.
- like sum, sort now also makes it possible to order items by attribute.
+- like sum and sort, join now also is able to join attributes of objects
+ as string.
+- the internal eval context now has a reference to the environment.
Version 2.5.5
-------------
View
@@ -256,7 +256,7 @@ def do_default(value, default_value=u'', boolean=False):
@evalcontextfilter
-def do_join(eval_ctx, value, d=u''):
+def do_join(eval_ctx, value, d=u'', attribute=None):
"""Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
@@ -268,7 +268,19 @@ def do_join(eval_ctx, value, d=u''):
{{ [1, 2, 3]|join }}
-> 123
+
+ It is also possible to join certain attributes of an object:
+
+ .. sourcecode:: jinja
+
+ {{ users|join(', ', attribute='username') }}
+
+ .. versionadded:: 2.6
+ The `attribute` parameter was added.
"""
+ if attribute is not None:
+ value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
+
# no automatic escaping? joining is a lot eaiser then
if not eval_ctx.autoescape:
return unicode(d).join(imap(unicode, value))
View
@@ -77,6 +77,7 @@ class EvalContext(object):
"""
def __init__(self, environment, template_name=None):
+ self.environment = environment
if callable(environment.autoescape):
self.autoescape = environment.autoescape(template_name)
else:
View
@@ -8,7 +8,6 @@
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
-import sys
from itertools import chain, imap
from jinja2.nodes import EvalContext, _context_function_types
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
@@ -128,6 +128,13 @@ def test_join(self):
tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}')
assert tmpl.render() == '&lt;foo&gt;<span>foo</span>'
+ def test_join_attribute(self):
+ class User(object):
+ def __init__(self, username):
+ self.username = username
+ tmpl = env.from_string('''{{ users|join(', ', 'username') }}''')
+ assert tmpl.render(users=map(User, ['foo', 'bar'])) == 'foo, bar'
+
def test_last(self):
tmpl = env.from_string('''{{ foo|last }}''')
out = tmpl.render(foo=range(10))

0 comments on commit 3383e1c

Please sign in to comment.