Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

nl2br filter

Posted by Dan Jacob on 2010-06-17 @ 05:03 and filed in Template Tricks

This is a nl2br (newline to <BR>) filter, adapted from the Jinja2 example here:

http://jinja.pocoo.org/2/documentation/api#custom-filters

import re

from jinja2 import evalcontextfilter, Markup, escape

_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')

app = Flask(__name__)

@app.template_filter()
@evalcontextfilter
def nl2br(eval_ctx, value):
    result = u'\n\n'.join(u'<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

This snippet by Dan Jacob can be used freely for anything you like. Consider it public domain.