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 pallets#486
  • Loading branch information
ThiefMaster committed Jan 6, 2017
1 parent e7e3752 commit 57b3c0d
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
Original file line number Diff line number Diff line change
Expand Up @@ -1253,7 +1253,11 @@ def visit_AssignBlock(self, node, frame):
self.blockvisit(node.body, block_frame)
self.newline(node)
self.visit(node.target, 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.pop_assign_tracking(frame)
self.leave_frame(block_frame)

Expand Down
2 changes: 1 addition & 1 deletion jinja2/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,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
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,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
Original file line number Diff line number Diff line change
Expand Up @@ -338,3 +338,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 57b3c0d

Please sign in to comment.