Render HTML tags from variable without escaping [duplicate]

主宰稳场 提交于 2021-02-19 02:11:26

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/31489609/render-html-tags-from-variable-without-escaping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!