Question

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.

Was it helpful?

Solution

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']

OTHER TIPS

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))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top