简体   繁体   中英

How do I pass Python list on Django template and use it in JavaScript?

I have a python list that has lists inside. I rendered it into Django template to use in my JavaScript. I did json.dumps(postImages) , and escaped with let postImages = {{ postImages|safe }} . And even tho my lint is giving a warning, it worked! But the problem is that, there are LISTS, inside of the main list. So whenever I do, postImages[0].length , or postImages[0][0] , it thinks that it is a string and now a list.

<script>
  var postImages = {{ postImages|safe }};
  const divCard = document.querySelector('.card');
  const divDesc = document.querySelector('.description');
  console.log(postImages.length)
  for (let i = 0; i < postImages.length; i++){
      let img = document.createElement('img');
      img.classList = ['resize_no_stretch', 'images']
      img.setAttribute('src', postImages[i][0]);
      console.log(postImages[i][0])
      divCard.insertBefore(img, divDesc);
  };
</script>

It is solved now. What I did was, I imported json on my views and instead of rendering it normally, I json.dumps() it.

views.py:

import json

postImages = json.dumps(list_of_lists)

return render(request, 'craiglist_clone/results.html', {'postImages' : postImages})

django template (craiglist_clone/results.html):

let postImages = {{ postImages|safe }}

Your lint my give you warning, but it still works!

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