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