Created
October 29, 2011 14:52
-
-
Save cemk/1324543 to your computer and use it in GitHub Desktop.
Creating linebreaks and paragraphs in Jinja2/Flask à la Django Style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(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)