Unicode strings in tornado web app

2020-04-21 06:47发布

问题:

How can I use unicode strings in tornado views or templates?
I insert in template
<meta http-equiv="content-type" content="text/html;charset=utf-8" /> And in view

# -- coding: utf-8 --
Output is ????

回答1:

Once you have your unicode string ready, the request should end

self.render("template.html", aString=aUnicodeString)

This renders the file "template.html" setting the aString variable to aUnicodeString.

template.html would look something like this:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    </head>
    <body>
        {{aString}}
    </body>
</html>

It's also possible to inline the HTML in the Tornado server.

self.render('<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body>{{aString}}</body></html>', aString=aUnicodeString)

More on templates here:

Tornado Web Server Documentation