biofractal
biofractal

Reputation: 19133

Using CoffeeScript string interpolation inside a for loop

I am filling an html <select> list with <option> elements based on a blob of JSON data. I would like to tidy up my code by using string interpolation but I cannot get the values to substitute correctly.

Here is the code that works (no interpolation):

$list
.empty()
.append('<option value="' + item.Id + '">' + item.Name + '</option>' for item in data)

Here is how I would like to do things (does not work):

$list
.empty()
.append('<option value="#{item.Id}">#{item.Name}</option>' for item in data)

Here is an example of the JSON I am using:

[
  {"Id":"1","Name":"Client-1"},
  {"Id":"2","Name":"Client-2"}
]

The substitutions do not happen, instead I just get a list filled with the correct number of #{item.Name} strings.

Is it possible to use CoffeeScript string interpolation inside a for loop like this?

Thanks.

Upvotes: 1

Views: 1495

Answers (1)

cspotcode
cspotcode

Reputation: 1892

String interpolation only works with double-quoted strings, not apostrophe-quoted strings.

http://coffeescript.org/#strings

This should work:

$list
.empty()
.append("<option value=\"#{item.Id}\">#{item.Name}</option>" for item in data)

Upvotes: 7

Related Questions