从变量呈现HTML标签而不进行转义 [英] Render HTML tags from variable without escaping

查看:192
本文介绍了从变量呈现HTML标签而不进行转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些HTML内容想要传递给模板进行渲染.但是,它转义了标记以使用HTML实体(<),因此它们显示为代码而不是标记.如何呈现传递到模板的html?

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

推荐答案

使用jinja2 safe 过滤器:

Use the jinja2 safe filter:

{{ tags | safe }}

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").

编辑

@davidism指出,还有另一种方法-建议将HTML传递到模板中:在python代码中使用Markup对象包装要传递到模板的html代码.

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 }}

将打印

some text here

这篇关于从变量呈现HTML标签而不进行转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆