LoginSignup
0
0

Flask から Jinja2 を通じて Javascript に辞書を渡す

Posted at

Flask から HTML に値を渡す場合

Jinja2 Template を使った HTML に Flask から値を渡す場合は

app.py
return render_template('index.html', name='りんご', price=100)
index.html
<body>
    <p> {{ name }}{{ price }}</p>
</body>
output
りんごは100円

Javascript で値や辞書を利用したい場合

Javascriptで値を利用したい場合は以下のように <script> タグの中で変数に代入
Python の Dictionary型 を渡したいときは json.dumps() で JSON に変換可能

app.py
fruit = {'name':'りんご', 'price':100}
return render_template('index.html', fruit=json.dumps(fruit))

JSONの場合は勝手にエスケープされてしまうことを防ぐために
safe オプションを追加します。

index.html
<head>
    <script> let fruit = {{ fruit|safe }} </script>
    <script src="static/js/main.js"></script>
</head>
main.js
console.log(`${fruit.name}${fruit.price}円`);
output
りんごは100円
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0