In my web app, the user can make blog posts. When I display the blog post, newlines aren\'t shown because I didn\'t replace the new lines with
tags.
The solution was to put <pre></pre>
tags around the area where I had the content.
You can create a jinja2 filter:
import re
from jinja2 import evalcontextfilter, Markup, escape
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
@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
You need to add the filter to your jinja2 Environment before you can use it:
JINJA2_ENV.filters['nl2br'] = jinja2_filters.nl2br
In your template you can use that filter:
{{post.content|nl2br}}