Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing <br> tags with Google App Engine and Jinja2

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?

like image 341
gsingh2011 Avatar asked May 03 '12 17:05

gsingh2011


3 Answers

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 %}
like image 161
gsingh2011 Avatar answered Oct 19 '22 00:10

gsingh2011


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.

like image 36
dav1d Avatar answered Oct 18 '22 22:10

dav1d


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>
like image 2
thakis Avatar answered Oct 18 '22 23:10

thakis