问题
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 }}
'< some text here >'
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