In Jinja2.7 the following URLs passed through the wordwrap filter with break_long_words=False still end up breaking on hyphens, periods, and slashes. In my case this is not desirable as I want URLs without white-space to not break at all.
Here's an example that wraps at the first "-" character:
{{ "https://docs.python.org/2/library/textwrap.html#textwrap.TextWrapper.wrap-this-lineis-goingtowrap"|wordwrap(73, False) }}
Adding the following custom wordwrap function which sets break_on_hyphens=False and invoking with customwordwrap() corrects the issue:
@environmentfilter
def do_customwordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None, break_on_hypens=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`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words,
break_on_hyphens=break_on_hypens))
{{ "https://docs.python.org/2/library/textwrap.html#textwrap.TextWrapper.wrap-this-lineis-goingtowrap"|customwordwrap(73, False) }}
This also corrects wrapping on '.' and on '/' in long unbroken URLs as well.
I suggest exposing break_on_hypens as a parameter to the wordwrap filter as was done with break_long_words as demonstrated by the custom wordwrap filter I provided.
In Jinja2.7 the following URLs passed through the
wordwrapfilter withbreak_long_words=Falsestill end up breaking on hyphens, periods, and slashes. In my case this is not desirable as I want URLs without white-space to not break at all.Here's an example that wraps at the first "-" character:
{{ "https://docs.python.org/2/library/textwrap.html#textwrap.TextWrapper.wrap-this-lineis-goingtowrap"|wordwrap(73, False) }}Adding the following custom wordwrap function which sets
break_on_hyphens=Falseand invoking withcustomwordwrap()corrects the issue:{{ "https://docs.python.org/2/library/textwrap.html#textwrap.TextWrapper.wrap-this-lineis-goingtowrap"|customwordwrap(73, False) }}This also corrects wrapping on '.' and on '/' in long unbroken URLs as well.
I suggest exposing
break_on_hypensas a parameter to thewordwrapfilter as was done withbreak_long_wordsas demonstrated by the custom wordwrap filter I provided.