Reputation: 4669
I want to push some server-side data into my javascript for display purposes. I have a list of serializable dictionary objects representing pieces of my data model that I want to use in javascript. These objects are defined as such:
event_types = EventType.objects.all()
et = []
for t in event_types:
et.append({'name' : t.name, 'internal_name' : t.internal_name}) # both names are strings
I push these up in the context variable to my template, and try to add it to javascript:
<script type="text/javascript">
var event_types = {{event_types}};
</script>
This doesn't work, as I get "Unexpected token '&'" as a javascript error. I then try commenting out that code and seeing what renders, and this is what I see:
[{'name': u'My Event', 'internal_name': u'my_event'}];
Clearly that is not desirable formatting. What is the correct way of pushing server-side Django data up to Javascript?
Upvotes: 0
Views: 3004
Reputation: 49816
The formatting you see is because the objects you pass to the template are being converted to strings using their repr
representations, and those strings are then being html encoded (so that if they were displayed on a page as text, you'd see the correct python repr
on the page).
What you want is to convert your objects to Javascript syntax, and not encode them further.
Fortunately, the builtin json.dumps
will convert your objects to JSON. You also need to turn escaping off for the block:
{% autoescape off %}
<script type="text/javascript">
var event_types = {{event_types}};
</script>
{% endautoescape %}
Upvotes: 2