Search code examples
pythontornado

Unicode strings in tornado web app


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


Solution

  • 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