LoginSignup
12
11

More than 3 years have passed since last update.

[Django]テンプレートタグから直接JavaScriptの変数に値を渡す方法

Last updated at Posted at 2020-05-24

Background

TemplateViewcontext_dataからhtmlにそのまま表示させたい時、下記の通りでタグをセットすると表示することができます。

views.py
from django.views.generic import TemplateView

class SampleTemplateView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['areas'] = ["japan","tokyo","osaka","nagoya","sapporo","sendai","fukuoka"]
        return context
index.html
...
    <ul>
    {% for item in areas %}
        <li> {{ item }} </li>
    {% endif %}
    </ul>
...
  • japan
  • tokyo
  • osaka
  • nagoya
  • sapporo
  • sendai
  • fukuoka

と表示。

しかし、Javascriptのライブラリを使って描画させたい時に直接値を渡したい場合があります。
ここでは渡す方法を紹介します。

Failure

そのまま渡すと、、、

<script type="text/javascript">
    var areas = "{{ areas }}";
    console.log(areas);
</script>
[&#x27;japan&#x27;, &#x27;tokyo&#x27;, &#x27;osaka&#x27;, &#x27;nagoya&#x27;, &#x27;sapporo&#x27;, &#x27;sendai&#x27;, &#x27;fukuoka&#x27;]

となってシングルクオテーション、"<"、">"などが自動で変換されます。
文字列型なので正規表現で置換した後に JSON.parse でdict化でいいかなと思ったのですがうまくできず。

で、調べた結果二つの方法を見つけました。

Method 1

泥臭いですが、各要素を呼び出してjavascriptコードに書き込む方法です。

var areas = [
{% for area in areas %}
{% with index=forloop.counter0 %}
{% if 0 < index%},{% endif %}
{% endwith %}
"{{area.name}}"
{% endfor %}
];
console.log(areas);

Method 2

もう一つは、autoescapeで⾃動エスケープ制御をoffにする方法です。

{% autoescape off %}
var areas = {{ areas }};
{% endautoescape %}
console.log(areas);

こっちの方がラクです。

Reference

12
11
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
12
11