Skip to content
Myr

Fix broken nl2br filter example

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This example attempts to handle both Windows-style and Unix-style line endings, but does it wrong; as noted at https://stackoverflow.com/q/12521127/1709587, the regex here will match a single \r\n as if it were a double line-break, which results in all single Windows-style line-breaks getting converted into <p> breaks instead of <br> breaks as intended. This patch fixes that by applying Alan Moore's proposed fix from https://stackoverflow.com/a/12521544/1709587 of using a negative lookahead so that a \r cannot be counted as a line break if it is followed by a \n (while still allowing the \r\n combination to count as a line break).

authored by Mark Amery · committed by Mark Amery · parent a7f1f52 · Browse files · 1 file+1 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+1 added−1 removed

  • other:+1 added−1 removed

1 file+1 added−1 removed

modified:docs/api.rst+1 added-1 removed
738 unmodified lines
739740 import re741 from jinja2 import evalcontextfilter, Markup, escape742743 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')743 _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')744745 @evalcontextfilter746 def nl2br(eval_ctx, value):747 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))
185 unmodified lines