Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape string interpolation in Coffeescript

I am trying to use this section of code from jQuery UI's tabs example and convert it to Coffeescript. I've run it through the awesome http://js2coffee.org/ tool.

var tabTitle = $( "#tab_title" ),
    tabContent = $( "#tab_content" ),
    tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
    tabCounter = 2;

The problem is that tabTemplate variable declaration. Coffeescript is trying to do string interpolation on it, as far as I can tell. I've tried escaping it with a slash, but that just resolves to using a slash in the converted js.

like image 812
Dan Avatar asked Dec 22 '11 18:12

Dan


2 Answers

Use single-quotes to delimit your string: http://coffeescript.org/#strings

If you want to use single-quotes within your string without manually escaping them you can use 3 single-quotes:

x = '''
my string's ok with single quotes and #{doesn't interpolate}
'''

That said, this is HTML, so double-quotes are actually more common for attributes than single-quotes. Your string could therefore be written as:

tabTemplate = '<li><a href="#{href}">#{label}</a> <span class="ui-icon ui-icon-close">Remove Tab</span></li>'

without any problems.

like image 147
nicolaskruchten Avatar answered Oct 03 '22 09:10

nicolaskruchten


Escaping with backslash does work:

$ coffee -bce '"\#{a}"'
"\#{a}";

$ coffee -bce '"#\{a}"'
"#\{a}";
like image 35
matyr Avatar answered Oct 03 '22 09:10

matyr