-
-
Save AndersonFirmino/23fb3e5bdc0a5c7075767ada70557f1e 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