1

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.

1
  • You're looking for HTML Templating, which coffeescript does not have. If you're trying to avoid string concatenation, just build the element via jQuery methods instead of appending a string. Commented Mar 12, 2013 at 14:41

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

3 Comments

That worked. Thanks. So is it best practice to use double-quoted strings throughout all of CoffeeScript? I am never sure what to use these days.
@biofractal: I single quote unless I need to double quote, that way a double quote indicates that there is code to look at rather than just a string literal. I do the same thing in all languages that have interpolation.
If you use """<option value="#{item.Id}">#{item.Name}</option>""" for item in data you do not have to escape each double quote inside the string.

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.