javascript 如何在 Coffeescript 中转义字符串插值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8608292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:58:42  来源:igfitidea点击:

How to escape string interpolation in Coffeescript

javascriptcoffeescript

提问by Dan

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.

我正在尝试使用 jQuery UI 的选项卡示例中的这部分代码并将其转换为 Coffeescript。我已经通过很棒的http://js2coffee.org/工具运行了它。

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.

问题在于tabTemplate 变量声明。据我所知,Coffeescript 正在尝试对其进行字符串插值。我试过用斜线转义它,但这只是解决在转换后的 js 中使用斜线。

回答by nicolaskruchten

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

使用单引号分隔您的字符串:http: //coffeescript.org/#strings

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

如果你想在你的字符串中使用单引号而不手动转义它们,你可以使用 3 个单引号:

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:

也就是说,这是 HTML,所以双引号实际上比单引号更常见于属性。因此,您的字符串可以写为:

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

without any problems.

没有任何问题。

回答by matyr

Escaping with backslash does work:

使用反斜杠转义确实有效:

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

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