import re
from jinja2 import evalcontextfilter, Markup, escape
_paragraph_re = re.compile('(?:\\r\\n|\\r|\\n){2,}')

@evalcontextfilter
def nl2br(eval_ctx, value):
    result = '\n\n'.join('<p>%s</p>' % p.replace('\n', '<br>\n') for p in
        _paragraph_re.split(escape(value)))
if eval_ctx.autoescape:
    result = Markup(result)
return result
How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?