1

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!

kramer65
  • 50,427
  • 120
  • 308
  • 488
  • 1
    try without curly braces and `'`.Jinja uses `{{` for variables – itzMEonTV Jun 03 '15 at 11:29
  • 1
    @itzmeontv - The thing is that this is part of an if statement. I edited the question to clarify this. – kramer65 Jun 03 '15 at 11:41
  • 1
    possible duplicate of [Passing HTML to template using Flask/Jinja2](http://stackoverflow.com/questions/3206344/passing-html-to-template-using-flask-jinja2) – plaes Jun 03 '15 at 13:20

2 Answers2

5

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 }}
plaes
  • 31,788
  • 11
  • 91
  • 89
0

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

Zyber
  • 1,034
  • 8
  • 19