Skip to content

Instantly share code, notes, and snippets.

@cemk
Created October 29, 2011 14:52
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cemk/1324543 to your computer and use it in GitHub Desktop.
Save cemk/1324543 to your computer and use it in GitHub Desktop.
Creating linebreaks and paragraphs in Jinja2/Flask à la Django Style
import re
from jinja2 import evalcontextfilter, Markup, escape
@app.template_filter()
@evalcontextfilter
def linebreaks(eval_ctx, value):
"""Converts newlines into <p> and <br />s."""
value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines
paras = re.split('\n{2,}', value)
paras = [u'<p>%s</p>' % p.replace('\n', '<br />') for p in paras]
paras = u'\n\n'.join(paras)
return Markup(paras)
@app.template_filter()
@evalcontextfilter
def linebreaksbr(eval_ctx, value):
"""Converts newlines into <p> and <br />s."""
value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines
paras = re.split('\n{2,}', value)
paras = [u'%s' % p.replace('\n', '<br />') for p in paras]
paras = u'\n\n'.join(paras)
return Markup(paras)
@floer32
Copy link

floer32 commented Aug 21, 2017

(Blast from the past) Thanks for this, I needed a quick answer on it and it was helpful to me. I ended up doing something a little different, have put my fork here (for anybody else who stumbles here from searching)

@miratcan
Copy link

miratcan commented Nov 9, 2020

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment