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});
3
  • 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. Commented Dec 18, 2017 at 10:39
  • you can use eval to convert string to object at javascript Commented Dec 18, 2017 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? Commented Dec 18, 2017 at 10:45

2 Answers 2

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(',');
Sign up to request clarification or add additional context in comments.

Comments

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}};

1 Comment

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.