Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render HTML tags from variable without escaping [duplicate]

I have some HTML content that I want to pass to the template to render. However, it escapes the tags to use HTML entities (<), so they show up as code rather than markup. How can I render the html passed to the template?

tags = """<p>some text here</p>"""
render_template ('index.html',tags=tags)
{{ tags }}
'&lt; some text here &gt;'

I want a paragraph with the text though.

some text here
like image 411
OMG coder Avatar asked Jul 18 '15 09:07

OMG coder


1 Answers

Use the jinja2 safe filter:

{{ tags | safe }}

safe filter tells the template engine to not auto-escape the string (because you escaped it manually or you're sure the string is safe). So, if the string is introduced by the user and you didn't escape it, it could rise security problems ("Don't trust the user").

EDIT

As @davidism pointed there is another method - the recomended one - to pass HTML into the template: using the Markup object in your python code to wrap the html code you want to pass to the template.

tags = Markup("<p>some text here</p>")

and in your template you only use:

{{ tags }}

which will print

some text here

like image 60
doru Avatar answered Oct 30 '22 16:10

doru