Reputation: 503
I have tried to convert python string data separated by commas into a javascript array variable but the process does not seem to be working.
these are my current codes:
var tagstring = {{ tag_data }};
var availableTags = new Array();
var availableTags = tagstring.split(",");
I need the array to look something like this:
var availableTags = ["Google App Engine","jQuery"];
Any ideas?
EDIT:
These are the working codes, thanks to the stackoverflow community :)
var tagstring = "{{ tag_data }}";
var availableTags = new Array();
var availableTags = tagstring.split(",");
Basically, even though the python variable is a string, it still needs to be specified as a string variable in javascript
Upvotes: 0
Views: 1420
Reputation: 318508
The proper solution is not using any string functions - be it in python or javascript - but a JSON encoder:
var availableTags = {{ json.dumps(elem.strip() for elem in tag_data.split(',')) }}
Of course it would be much nicer if you had a list in python instead of a string...
Upvotes: 1
Reputation: 98746
Assuming this is in a Django template, then this should work:
var tagstring = "{{ tag_data|escapejs }}";
I've added quotation marks ("
) around the tag_data
, since otherwise just the literal text in the string will be inserted into the Javascript; you want to construct a Javascript string that contains this value.
I've also used the escapejs
tag to avoid problems with embedded backslashes, etc.
Upvotes: 3
Reputation: 338208
What does
var tagstring = "{{ tag_data }}";
var availableTags = tagstring.split(",");
produce?
By the way, this can further be collapsed into a one-liner.
var availableTags = "{{ tag_data }}".split(",");
Upvotes: 1