views:

1537

answers:

3

I am trying to assign some javascript variables in a Django template.

I am having a problem where the values I am assigning are being written to the page properly (I can see them in the page source), but still come up as null.

I am doing this:

<script type="text/javascript">
  var coords = [];
  {% for i in item_list %}
    coords.push([ {{i.x}}, {{i.y}} ]);
  {% endfor %}
</script>

This is the page source that is produced:

coords.push([ -320.435118373, -149.333637576 ]);
coords.push([ -120.41321373 , -329.312376 ]);
...

It seems to be perfectly valid javascript, however, using Firebug to view the value of coords, this is what is produced:

[[null, null], [null, null], [null, null]...[null, null]]

So it's apparent that each of the push() calls is going off correctly and a new array of size 2 is being added each time. However, for some reason, the numeric literals all evaluate to null.

Does anyone know how I can get these values to be used properly?

UPDATE: It appears that the values in the array are fine until I pass them into the jQuery flot plugin:

$.plot($('#mapWrapper'), coords, options);

So I guess this doesn't have anything to do with the way I am using the Django templates after all. Still, I am curious as to what the problem is with $.plot.

A: 

I've tried this out in a test app and it works fine (with item_list being a list of dicts with floats as the "x" and "y" elements). There must be something else you're doing that you're not showing here.

I wonder if maybe it's a weird encoding issue, maybe you're using weird unicode characters without realizing it?

Thomas Parslow
A: 

What exactly is plot meant to do? It sounds as though it should be working with the coords somehow, in which case is it correct to pass in an array of arrays for the points?

I would have expected that to take an array of hashes or Coords objects, something like:

coords.push({ "x":-320.435118373, "y":-149.333637576 });
coords.push({ "y":-120.41321373, "y":-329.312376 });

Just a thought.

Andy Hume
flot does take an array of arrays for the data series. This is my first time using flot, but I've used flotr a lot (a copycat for prototype), and the documentation indicates the same usage.
TM
A: 

Looks like I was missing one small thing. I was using a data series which was an array of arrays. Actually, the jquery flot plugin is expecting an array of series, which are arrays of arrays, so I needed a triple-nested array.

Changing from this:

$.plot($('#mapWrapper'), coords, options);

to this:

$.plot($('#mapWrapper'), [coords], options);

fixed the problem.

Thanks to all who looked at this.

TM