Reputation: 45
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});
Upvotes: 1
Views: 4768
Reputation: 31
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(',');
Upvotes: 3
Reputation: 77902
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}};
Upvotes: 0