0

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:

[{&#39;name&#39;: u&#39;My Event&#39;, &#39;internal_name&#39;: u&#39;my_event&#39;}];

Clearly that is not desirable formatting. What is the correct way of pushing server-side Django data up to Javascript?

Jim
  • 4,509
  • 16
  • 50
  • 80

1 Answers1

2

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 %}
Marcin
  • 48,559
  • 18
  • 128
  • 201
  • -1 I wouldn't do this since you're creating global javascript varaibles here, just because you can doesn't mean you should. I would open an endpoint and deliver this list as json. – Henrik Andersson Aug 07 '14 at 12:26
  • @limelights So, you're saying that I should have answered the question you wish OP had asked? Excuse me if I answer the actual question. As to your suggestion, that will have worse performance than packing everything into a single request. – Marcin Aug 07 '14 at 13:42
  • No, what I'm saying is that whilst you answered the question the answer IMO in this case should also reflect on what the OP can improve upon and not further worsen the OP's code by introducing bad practices. – Henrik Andersson Aug 07 '14 at 13:50
  • @limelights Yes, but you're simply wrong that this is a bad practice. – Marcin Aug 07 '14 at 15:11
  • I'm not wrong, we're just not agreeing. http://yuiblog.com/blog/2006/06/01/global-domination/ – Henrik Andersson Aug 07 '14 at 15:51