Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wordwrap replace whitespace #82

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions jinja2/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,17 +444,19 @@ def do_truncate(s, length=255, killwords=False, end='...'):
return u' '.join(result)

@environmentfilter
def do_wordwrap(environment, s, width=79, break_long_words=True):
def do_wordwrap(environment, s, width=79, break_long_words=True,
replace_whitespace=False):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`.
"""
import textwrap
return environment.newline_sequence.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
res = textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=replace_whitespace,
break_long_words=break_long_words)
return environment.newline_sequence.join(res)


def do_wordcount(s):
Expand Down
12 changes: 12 additions & 0 deletions jinja2/testsuite/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,18 @@ def test_urlize(self):
assert tmpl.render() == 'foo <a href="http://www.example.com/">'\
'http://www.example.com/</a> bar'

def test_wordwrap(self):
s = ' '.join('lots of words' for i in range(40))
tmpl = env.from_string('{{ s|wordwrap(80) }}')
wraped = tmpl.render(s=s)
for l in wraped.splitlines():
assert len(l.rstrip()) <= 80
tmpl = env.from_string('{{ s|wordwrap(80, false) }}')
assert tmpl.render(s="hugeword"*40).count("\n") == 0
tmpl = env.from_string('{{ s|wordwrap(80, replace_whitespace=true) }}')
s = '\n'.join('lots of words' for i in range(40))
assert tmpl.render(s=s) == wraped

def test_wordcount(self):
tmpl = env.from_string('{{ "foo bar baz"|wordcount }}')
assert tmpl.render() == '3'
Expand Down