Frage

I need help understanding behavior of render_string in tornado. I am using below code.

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>

if message["html"] is data then the output of to_basestring is

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

Now, if message["html"] is <img src="/media//uploads/Capture_23.PNG" />

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

From the documentation , this function 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.
"""

It does not mention anything about escaping/unescaping html tags . How can I use this function , so that if message["html"] is <img src="/media//uploads/Capture_23.PNG" /> ,

I get output as

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

Lösung

The tornado template system automatically escapes everything except the output of modules or the raw directive; modules are expected to do their own escaping. In this case the escaping is actually done by the linkify module.

linkify takes plain text and turns it into html, so it must assume that any angle brackets are meant to be shown verbatim, and escapes them. You don't want to actually pass <img> tags through linkify because it's not smart enough to see the src attribute, and if you had an absolute url it would become <img src="<a href="url">url</a>">.

If you want to include message["html"] with no escaping, the simplest way is to use the raw directive: {% raw message["html"] %}. See the template docs at http://www.tornadoweb.org/en/stable/template.html

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top