3

I am using Flask render_template method to render my html page as below:

render_template('index.html', content="<div>Hello World!</div>")

My index.html is:

<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
{{content}}
</body>
</html>

My page is replacing the content variable, but it is rendering <div>Hello World!</div> as text.

Is there a way to render html from render_template context variables?

Awesome
  • 5,689
  • 8
  • 33
  • 58

2 Answers2

8

Flask turns on Jinja's autoescape feature. Quoting the manual on how to disable it:

There are three ways to accomplish that:

  1. In the Python code, wrap the HTML string in a Markup object before passing it to the template. This is in general the recommended way.

  2. Inside the template, use the |safe filter to explicitly mark a string as safe HTML ({{ myvariable|safe }})`

  3. Temporarily disable the autoescape system altogether.

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15
0

If you do not require passing in HTML tags into the template, you may simply do something that looks like this


Template

<html lang="en">
<head>
<title>Hello</title>
</head>

<body>
    <div> 
        {{content}}
    </div>
</body>

</html>

Python code

@app.route('/')
def home():
    render_template('index.html', content="Hello World!")

This should be perfectly fine. If you do want to add html into your content variable, then the answer by @Ture Pålsson is the best way forward.

Jishnu P Das
  • 107
  • 4
  • 2
    If at all possible, this is probably a better approach than the one I suggested. It's a good idea to keep the HTML in the templates and out of the Python code! – Ture Pålsson Dec 16 '20 at 06:59