Skip to content

Instantly share code, notes, and snippets.

@Flushot
Created June 14, 2013 23:23
Show Gist options
  • Select an option

  • Save Flushot/5786047 to your computer and use it in GitHub Desktop.

Select an option

Save Flushot/5786047 to your computer and use it in GitHub Desktop.
Jinja2 filter that mimicks PHP's nl2br
import re
from jinja2 import evalcontextfilter, Undefined, Markup, escape
paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
@app.template_filter()
@evalcontextfilter
def linebreaks(eval_ctx, value):
if value is None or isinstance(value, Undefined):
return ''
result = u'\n\n'.join( '<p>%s</p>' % str(p).replace('\n', '<br/>'\n') \
for p in paragraph_re.split(escape(value)) )
if eval_ctx.autoescape:
result = Markup(result)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment