简体   繁体   中英

How to convert string variable from python into a javascript literal array?

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

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.

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(",");

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM