views:

76

answers:

2

Hi,

I have a javascript which takes two variables i.e two lists one is a list of numbers and the other list of strings from django/python

numbersvar = [0,1,2,3]
stringsvar = ['a','b','c']

The numbersvar is rendered perfectly but when I do {{stringsvar}} it does not render it.

+3  A: 

Maybe it will be better to use a json module to create a javascript lists?

>>> a = ['stste', 'setset', 'serthjsetj']
>>> b = json.dumps(a)
>>> b
'["stste", "setset", "serthjsetj"]'
>>> json.loads(b)
[u'stste', u'setset', u'serthjsetj']
Enchantner
+1 for using code that others have already debugged for you.
slebetman
How does one go about doing that? Can I create a string in a similar fashion?
Fahim Akhter
A: 

What does stringsvar contain? The list, or the string representation of the list?

I suggest you pass the correct javascript string representation of the list from the view method to the template to render. Python and javascript array literals have the same syntax, so you could do:

def my_view(request):
    return render_template("...", stringsvar=str(the_list))

And in the template:

<script language="javascript">
stringsvar = {{ stringsvar }};
...
</script>

Or you can use the json serializer, this has the added benefit that you will be able to pass other kinds of values as well.

from django.core import serializers
def my_view(request):
    return render_template("...", stringsvar=serializers.serialize("json", the_list))
codeape
stringsvar = ['stringone','stringtwo']I tried passing a string to javascript that did not work either.If I serialize the variable how do I de serialize it?
Fahim Akhter
You don't deserialize it. Using serializers.serialize("json", ...), you convert a python list to its javascript literal representation. That literal representation is passed to the template and output unchanged. So I guess you could say that javascript deserializes the variable when the script is evaluated.
codeape