Monday, April 8, 2013

Re: Accessing list of dictionaries in jQuery

Injecting data into a template can be tricky. I would recommend doing
two things:

1) Serialize your data to JSON in your view first using Python's json
module. Something like this:
>>> images_as_json = json.dumps(images)

2) Rather than trying to inject it directly into JavaScript, which can
cause encoding-related issues, dump your JSON-formatted string into a
hidden node on page, then read it out and parse it into a JS object. So,
for example:

<div style="display: none;" id="myData">{{ images_as_json }}</div>
<script type="text/javascript>
var images = $.parseJSON($('#myData').html();
</script>

_Nik

On 4/8/2013 4:53 PM, Larry Martell wrote:
> I am passing a list of dictionaries to my template. In the template
> language I can do this and it works as expected:
>
> {% for row in images %}
> <div class="gImage-row gImage_row-{{ forloop.counter0 }}">
> <a class='no-highlight' href="{{ IMAGE_DIR }}{{ row.image }}"
> rel="superbox[image]">
> <img class='gImage' src="{{ IMAGE_DIR }}{{ row.image }}"
> onerror="noimage(event)">
> </a>
> </div>
> {% endfor %}
>
> But I need to process this data in jQuery. If I pass images into a
> function like this:
>
> my_func({{ images }});
>
> I get a syntax error, 'unexpected token &'
>
> And if I pass it in like this:
>
> my_func("{{ images }}");
>
> It is received in the function as a character string, not as a list of
> dictionaries. How can I pass this to my function and have it be
> received as the list of dictionaries that it is?
>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate