【问题标题】:Rendering custom data in handsontable with the Tornado module in python使用python中的Tornado模块在handsontable中渲染自定义数据
【发布时间】:2018-04-05 05:03:02
【问题描述】:

我正在努力将数据从我的 tornado 网络服务器移动到 javascript handsontable。我认为问题与正确转义或编码我的数据有关,但我无法弄清楚。

这是python代码。我正在获取列表列表并将其编码为 json。

class hot_index(tornado.web.RequestHandler):
    def get(self):
        self.render("hot_tradedata.html",
                    data=json.dumps([
                            ['', 'Tesla', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'],
                            ['2017', 10, 11, 12, 13, 15, 16],
                            ['2018', 10, 11, 12, 13, 15, 16],
                            ['2019', 10, 11, 12, 13, 15, 16],
                            ['2020', 10, 11, 12, 13, 15, 16],
                            ['2021', 10, 11, 12, 13, 15, 16]
                                ])
                    )

if __name__ == "__main__":
    app = tornado.web.Application(
        handlers=[(r"/hot", hot_index)],
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        template_path=os.path.join(os.path.dirname(__file__), "templates")

这是可操作的代码。我希望表格中填充我在 python 函数中定义的数据。

<div id="example1"></div>

<script>
    var
    data1 = {{data}},
    container1 = document.getElementById('example1'),
    settings1 = {
      data: data1
    },
    hot1;

  hot1 = new Handsontable(container1, settings1);
  hot1.render();
</script>

浏览器控制台显示数据已成功传递到html页面,但看起来javascript不喜欢输入。我想我需要以不同的方式转义 {{data}}?

<body><div id="example1"></div>
<script>
var
data1 = [[&quot;&quot;, &quot;Tesla&quot;, &quot;Nissan&quot;, &quot;Toyota&quot;, &quot;Honda&quot;, &quot;Mazda&quot;, &quot;Ford&quot;], [&quot;2017&quot;, 10, 11, 12, 13, 15, 16], [&quot;2018&quot;, 10, 11, 12, 13, 15, 16], [&quot;2019&quot;, 10, 11, 12, 13, 15, 16], [&quot;2020&quot;, 10, 11, 12, 13, 15, 16], [&quot;2021&quot;, 10, 11, 12, 13, 15, 16]],
container1 = document.getElementById('example1'),
settings1 = {
data: data1
},
hot1;
hot1 = new Handsontable(container1, settings1);
hot1.render();
</script>

【问题讨论】:

    标签: javascript python tornado handsontable


    【解决方案1】:

    默认情况下 Tornado “自动转义”引号。您可以使用raw 函数正确渲染它

    <div id="example1"></div>
    
    <script>
        var
        data1 = {% raw data %},
        ...
    

    另一种解决方案是传递对象(不是 json)进行渲染,并在模板中使用 json_encode。我认为它看起来更干净,但如果你已经有 json 字符串(例如,你从其他来源收到)或者你有很大的 json 并且你想使用不同(更快)的实现(如 rapidjson、ujson),情况并非如此比json_encode.

    更多信息http://www.tornadoweb.org/en/stable/template.html#syntax-reference

    【讨论】:

    • 哪种方法是最佳实践?以一种方式或另一种方式这样做有优缺点吗?
    猜你喜欢
    • 2015-03-29
    • 2018-05-28
    • 2015-01-01
    • 2017-11-06
    • 2013-07-17
    • 2016-02-03
    • 2020-04-03
    • 1970-01-01
    • 2016-12-03
    相关资源
    最近更新 更多