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 <br>
tags. The problem is that I've turned autoescaping on in Jinja, so <br>
tags are escaped. I don't want to temporarily disable autoescaping, I want to specifically allow <br>
tags. How would I do this?
I have another answer that I think is the best. Initially I was just displaying my variable post.content
as-is, and the newlines weren't being preserved. None of the solutions here worked (well), and my pre solution was just a quick fix and had major issues. This is the real solution:
{% for line in post.content.splitlines() %}
{{line}}<br>
{% endfor %}
You can use the |safe
filter, or use the autoescape blocks:
{% autoescape false %}
{{ content goes here }}
{% autoescape %}
You could also set autoescaping in the environment to False
.
In your model object, add a function like this:
class Post(db.Model):
# ...
def html_content(self):
# Escape, then convert newlines to br tags, then wrap with Markup object
# so that the <br> tags don't get escaped.
def escape(s):
# unicode() forces the conversion to happen immediately,
# instead of at substitution time (else <br> would get escaped too)
return unicode(jinja2.escape(s))
return jinja2.Markup(escape(self.content).replace('\n', '<br>'))
Then in your template, just call that:
<p>{{ post.html_content() }}</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With