Question

I am trying to put an array from a server to a web page via jinja2 in google app engine, but I can't seem to get it so it is readable by my jQuery code. I'm pretty new--first time I've tried something like this.

My python code looks like this (with some code removed for brevity):

import json
jinja2_ENVIRONMENT.filters['json'] = json.dumps

filterList = ["context","home"]
template_values = {
"filterList" : filterList
}

which I pass to the output by using :

self.response.write(template.render(template_values))

the attribute in my html template looks like this:

filterlist="{{ filterList|json }}"

My problem is that the array is not readable by the javascript on the browser. In the element inspector it looks like this:

filterlist="["context", "home"]"

while for JSON, I THINK I want something like '["context","home"]' for it to be readable by my jQuery code. [edit: it is readable, but as a string, not as an array... I'd rather not have to write a parser if I don't have to].

var filterList = $("body").attr("filterlist");

Thank you for your help.

Was it helpful?

Solution 2

I tried everything suggested above, but still had some problems. In the end, I was able to find a solution using the JSON.parse() method. By adding the following line to my jQuery code:

var filterList = JSON.parse('{"filterList":'+$tasklist.attr("filterlist")+'}');

I was able to access the array as filterList.filterList.

I'm not sure where I went wrong, but I suspect somehow I am not using the jinja2 python library correctly. Nonetheless, this solution worked for me.

OTHER TIPS

You're already passing JSON to the template. So just output it using:

filterlist={{ filterList|safe }};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top