Skip to content

Commit

Permalink
Support filters in set block
Browse files Browse the repository at this point in the history
- e.g {% set foo | trim %}...{% endset %}
- closes #486
  • Loading branch information
ThiefMaster committed Sep 11, 2015
1 parent 50c6cd7 commit 14cdc77
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 3 deletions.
6 changes: 5 additions & 1 deletion jinja2/compiler.py
Expand Up @@ -1412,7 +1412,11 @@ def visit_AssignBlock(self, node, frame):
assignment_frame = self.make_assignment_frame(frame)
self.newline(node)
self.visit(node.target, assignment_frame)
self.write(' = concat(%s)' % block_frame.buffer)
if node.filter is not None:
self.write(' = ')
self.visit_Filter(node.filter, block_frame)
else:
self.write(' = concat(%s)' % block_frame.buffer)
self.export_assigned_vars(frame, assignment_frame)

# -- Expression Visitors
Expand Down
2 changes: 1 addition & 1 deletion jinja2/nodes.py
Expand Up @@ -349,7 +349,7 @@ class Assign(Stmt):

class AssignBlock(Stmt):
"""Assigns a block to a target."""
fields = ('target', 'body')
fields = ('target', 'filter', 'body')


class Expr(Node):
Expand Down
3 changes: 2 additions & 1 deletion jinja2/parser.py
Expand Up @@ -171,9 +171,10 @@ def parse_set(self):
if self.stream.skip_if('assign'):
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno)
filter_node = self.parse_filter(None)
body = self.parse_statements(('name:endset',),
drop_needle=True)
return nodes.AssignBlock(target, body, lineno=lineno)
return nodes.AssignBlock(target, filter_node, body, lineno=lineno)

def parse_for(self):
"""Parse a for loop."""
Expand Down
7 changes: 7 additions & 0 deletions tests/test_core_tags.py
Expand Up @@ -335,3 +335,10 @@ def test_block(self, env_trim):
tmpl = env_trim.from_string('{% set foo %}42{% endset %}{{ foo }}')
assert tmpl.render() == '42'
assert tmpl.module.foo == u'42'

def test_block_filtered(self, env_trim):
tmpl = env_trim.from_string(
'{% set foo | trim | length | string %} 42 {% endset %}'
'{{ foo }}')
assert tmpl.render() == '2'
assert tmpl.module.foo == u'2'

0 comments on commit 14cdc77

Please sign in to comment.