kramer65
kramer65

Reputation: 54013

Flask html not rendered when using Jinja2 templating tag

I'm using the (awesome) Flask framework to build a website and I now have a problem with html not being rendered properly. I've got a line in my template with an if-else depending on whether the public variable is True:

{{ theInfo if public else '<span style="background-color: green;">this info is hidden</span>' }}

Unfortunately, this simply displays the html in the browser, instead of rendering it. Do I need to somehow let Jinja know that its html should be rendered?

All tips are welcome!

Upvotes: 1

Views: 3148

Answers (2)

plaes
plaes

Reputation: 32766

By default Jinja escapes the passed data. Therefore you need to explicitly tell Jinja that data is safe to use:

{{ theInfo if public else '<span style="background-color: green;">this info is hidden</span>' | safe }}

Upvotes: 5

Zyber
Zyber

Reputation: 1034

If you want to display different html based on a value you need to first send this value in your call to render_template

python

def view():
   variablename = True
   return flask.render_template('page.html', public=variablename)

To check this value you add an if statement inside curly brackets, see code below

html

{% if public %}
    <p>Public is true!</p>
{% else %}
    <span ..../>
{% endif %}

A good first step is to go through the tutorial by Miguel Grinberg. http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

Upvotes: 0

Related Questions