龙卷风| render_string用法

时间:2014-04-29 09:42:11

标签: html templates tornado

我需要帮助理解龙卷风中render_string的行为。  我正在使用下面的代码。

tornado.escape.to_basestring(self.render_string("message.html", input_to_template=message))

message.html

<div class="message">{% module linkify(input_to_template["body"]) %}</div>

如果message["html"]data,则to_basestring的输出为

<div class="message">data</div>\n

现在,如果message["html"]<img src="/media//uploads/Capture_23.PNG" />

<div class="message">&lt;img src=&quot;/media//uploads/Capture_23.PNG&quot; /&gt;</div>\n

来自documentation,此函数render_string

"""
Generate the given template with the given arguments.    
We return the generated byte string (in utf8). To generate and
write a template as a response, use render() above.
"""

它没有提及有关转义/取消转义html标记的任何内容。 我如何使用此功能,以便message["html"]<img src="/media//uploads/Capture_23.PNG" />

我输出为

<div class="message"><img src="/media//uploads/Capture_23.PNG" /></div>\n

1 个答案:

答案 0 :(得分:2)

龙卷风模板系统会自动转义除模块输出或raw指令之外的所有内容;模块应该自己逃避。在这种情况下,转义实际上是由linkify模块完成的。

linkify采用纯文本并将其转换为html,因此必须假设任何尖括号都是逐字显示的,并将其转义。您不希望通过<img>实际传递linkify代码,因为它不够智能,无法查看src属性,如果您有绝对网址,则会{{1} }}。

如果要包含<img src="<a href="url">url</a>">而不进行转义,最简单的方法是使用message["html"]指令:raw。请参阅http://www.tornadoweb.org/en/stable/template.html

上的模板文档