简体   繁体   中英

How to get python/Django lists/dictionaries into javascript

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?

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM