2017-10-24 4 views
0

私は竜巻ウェブサーバからjavascript handsontableにデータを移動するのに苦労しています。問題は、データを適切にエスケープしたりエンコードしたりすることに関連していると思いますが、わかりません。PythonでTornadoモジュールを使用して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> 

答えて

1

デフォルトでは、Tornadoの「autoescapes」は引用符で囲まれています。あなたはそれが正しくレンダリングするオブジェクト(ないJSONを)渡すraw機能

​​

他の解決策があるを使用してレンダリングしたテンプレートにjson_encodeを使用することができます。あなたが既にjson文字列(例えば、あなたが他のソースから受け取ったもの)を持っているか、大きなjsonを持っていて、jsonの別の(より速い)実装(rapidjson、ujsonのようなもの)を使用したいなら、 json_encodeより。

詳細情報http://www.tornadoweb.org/en/stable/template.html#syntax-reference

+0

どの方法がベストプラクティスですか?一方的にそれをすることに賛否両論はありますか? – rvictordelta

+0

私は答えを編集しました。 – kwarunek

関連する問題