0

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

6
  • 1
    Please post what {{ tag_data }} produces, exactly. Commented Mar 12, 2011 at 7:35
  • 2
    May I suggest using a Python JSON library instead to take data from Python and put it into Javascript? Commented Mar 12, 2011 at 7:40
  • My mistake was var tagstring should be = "{{ tag_data }}"; Commented Mar 12, 2011 at 7:52
  • @Gabe i have tried eval(), does not seem to work for me though. split is the best solution so far :) Commented Mar 12, 2011 at 7:53
  • Setting availableTags to a new Array() is useless here by the way, since it gets overwritten with a different array on the next line Commented Mar 12, 2011 at 7:56

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the escapejs filter. escape will not be necessary since there HTML-escaping is not needed (wrong, even) within a <script> tag.
by inserting |escapejs to {{ tag_data }}, would it affect my python variable that is retrieved over into the script?
@pivotal: No, the variable would remain unchanged; only the result would change
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.