deltanovember
deltanovember

Reputation: 44051

How can I feed a server side Django string array into a client side JavaScript array?

On my server the array appears as follows:

data = [u'Data1', u'Data2', u'Data3']

In Django, I send the data through to the client using:

render(..., {'data': data})

On the client side I try to render in JavaScript using:

{{data}}

and get:

[u'Data1B', u'Data2', u'Data3']

How can I fix this encoding issue?

Upvotes: 0

Views: 86

Answers (2)

LarsVegas
LarsVegas

Reputation: 6812

You can also pass your data as a json object. In your view.py

from django.utils import simplejson
...
render(...{'data':simplejson.dumps(data)})

and then in your javascript function

var data = JSON.parse({{data}}) 

But as @karthikr already said, |safe is your case absolutely sufficient.

Upvotes: 0

karthikr
karthikr

Reputation: 99620

You need to safe escape the string inorder to work fine

{{data|safe|escape}}

Upvotes: 2

Related Questions