4

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?

0

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.