1

Goal: I want to pass list of strings in Django to template JS as an array of strings and get index for each string in the array.

Problem: Javascript indexOf() is counting each character (e.g. letters, single quotes and brackets). My tries below are based on this, this and this.

Code 1: I tried escapejs and safe filters, but indexOf() is returning 2 for the first item in the array (should be 0).

#views.py
list = [#utf-8 encoded strings]
return render(request, template, {'list': list}) 

#template JS
 $('#id').ready(function() {
 var array = "{{list|escapejs}}";
 console.log(array.indexOf('{{obj}}'));
 #obj is item in list});

Code 2: Also tried json.dumps() with encode('utf8') or json.loads() but the problem persists.

#views.py
list = [#utf-8 encoded strings]
list = json.dumps(list, ensure_ascii=False).encode('utf8')
return render(request, template, {'list': list}) 

#template JS
 $('#id').ready(function() {
 var array = "{{list}}";
 console.log(array.indexOf('{{obj}}'));
 #obj is item in list});
useruser
  • 45
  • 1
  • 7
  • 1
    `var array = "{{list}}";` exits the templating process as something like the this: `var array = "[\"first\", \"second\"]";`. That is to say that it is a string, not an array. – Kendas Dec 18 '17 at 10:39
  • you can use eval to convert string to object at javascript – Harsha Biyani Dec 18 '17 at 10:40
  • If you are trying to send json objects from front-end to back-end - why not go with a REST API built with django rest framework in the first place? – Deniz Saner Dec 18 '17 at 10:45

2 Answers2

3

Another option is to turn a Python list of strings into a string with join:

list = ','.join(list)
return render(request, template, {'list': list})

and then split it again with JS in your template:

var array = "{{ list }}".split(',');
Filip Hałoń
  • 31
  • 1
  • 4
0

As Kenda mentions in a comment, this:

var array = "{{list}}";

will make array a string containing the representation of your list (either the Python list itself or it's json representation). What you want is to dump your list to json (to make sure you have a native javascript representation of your Python list) as you already tried AND avoid adding the quotes in the JS snippet:

var array = {{list}};
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Thanks so much! I actually tried it without the double quotes but my `JSLint` was returning errors... Lesson learned: Don't blindly follow what the linter tells you :) – useruser Dec 18 '17 at 23:26