Search code examples
pythonhtmltornado

how to send html object from python to web page Tornado


Inside my python code I have a html code for table

import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        tables = "<table>  <tr>    <th>Company</th>            <th>Contact</th>    <th>Country</th>  </tr>  <tr>    \
    <td>Alfreds Futterkiste</td>     <td>Maria Anders</td>    <td>Germany</td>  </tr>  <tr>    \
    <td>Centro comercial Moctezuma</td>    <td>Francisco Chang</td>     <td>Mexico</td>  </tr>  <tr>    \
    <td>Ernst Handel</td>    <td>Roland Mendel</td>    <td>Austria</td>  </tr>  <tr>  <td>Island Trading</td>    \
    <td>Helen Bennett</td>    <td>UK</td>  </tr>  <tr>    <td>Laughing Bacchus Winecellars</td> \
    <td>Yoshi Tannamuri</td>    <td>Canada</td>  </tr>  <tr>    <td>Magazzini Alimentari Riuniti</td>    \
    <td>Giovanni Rovelli</td> <td>Italy</td>  </tr> </table>"


        self.render('index.html',tableinfo = tables)
if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = tornado.web.Application(
        handlers=[(r'/', IndexHandler)],
        template_path=os.path.join(os.path.dirname(__file__), "templates"))
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

I plan to print this table in the index.html file

<!DOCTYPE html>
<html>
<head><title>Help For table print</title></head>
<body>
<p> {{tableinfo}}  </p>
</body>
</html>

unfortunately it is only prints the string into the html code and does not use the code to create the table. Could you please help me to show the table by exchanging variables. Many thanks


Solution

  • Tornado template output is escaped by default. To include raw html, use the raw template directive (and be careful of XSS!): {% raw tableinfo %}