简体   繁体   中英

How to send dict of dict from Django to javascript

I want to send data from Django to JavaScript so I can write all logic in JS + Vue and keep html clean.

In Django I have

context={'names':{'fn':'john','ln':'cena'}}
return render(request,'app/page1.html',context)

in page1.html template I have

<script type="text/javascript"> var names="{{names}}"; </script>

In javascript how can I access names.fn & names.ln ?

I have two more related questions:

  1. Is this a preferred Django way to send data directly from Django to JS when template is rendered. (The only other method I know is through Ajax call. Here I dont want to do additional Ajax call after the page is rendered)
  2. From security stand point, is it better to keep Django data related logic {% if x > y %} inside templates or is it ok to move the logic part to JS + Vue and just keep data structure in the template. I ask this because when i check page source in a browser window, I can see entire JS code but I cannot see anything that's inside a Django condition statement in html : {% if x>y %} ----THIS IS INVISIBLE IN A BROWSER---- {% endif %}

Thanks

There's json_script :

{{names|json_script("names")}}

and then, in JS:

var names = JSON.parse(document.getElementById('names').textContent);

Alternately, install django-jsonify ; then, you can directly say

{% load jsonify %}
<script type="text/javascript"> var names={{names|jsonify}}; </script>

As for your second question: everything Vue (or Angular or React or Ractive or Knockout...) does is clientside, everything Django does is serverside. If you're building a Single-Page Application, you should prefer to do as much as possible using Vue (or Angular or React or Ractive or Knockout...); if you are not, then you likely don't need such a framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM