4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Django データをjavascriptで扱えるようにする

Posted at

djangoのviews.pyからデータをhtmlに送り、その後javasciriptで使用するようにする。

以下の3つのファイルを使用する

views.py
def index(request):
  data_value = 'sample'
  context = {'data_key':data_value}
  return render(request,'index.html,context)
index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    let data = {{data_key | safe }};
  </script>
  {% if data_key is not None %}
    <div class="mdl-layout__container">
  {%else%}
    error
  {%endif%}
</div>
  <script type="text/javascript" src="{% static 'index.js' %}"></script>
</body>
</html>
index.js
console.log(data)

まず、contextでは{'key':value} で送ってあげる
html上では、scriptタグを用いて、let data = {{data | safe}}
のような形で取ってあげる。
|safeはHTMLタグを描き出せるようにするためのフィルター機能
その後、jsファイルを読み込んで、書き出しを行う。
これにより、データをjsファイル上で 扱えるようになる。

4
6
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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?