Search code examples
pythonhtmltornado

Render html response from string in python tornado library


I need to render response from html string in tornado like this:

self.method_to_render_html_from_string('<h1>Hello</h1>')

How can I do it? Tornado version is 6.1. Here how it's displayed as for now: enter image description here

Answers, not related to tornado, are appreciated too :)


Solution

  • If you want to send a response, use self.write:

    def get(self):
        self.write('<h1>Hello</h1>')
    

    If you want to generate html from template string, then use tornado.template.Template:

    from tornado.template import Template
    
    def get(string):
        t = Template('<h1>Hello {{ name }}</h1>')
        self.write(t.generate(name='John'))
    

    Update:

    If the response is being sent as plain text, you can try setting the Content-Type: text/html header to send the response as HTML:

    def get(self):
        self.set_header('Content-Type', 'text/html')
        self.write('<h1>Hello</h1>)