javascript Handlebars 特定 - 传递 Handlebars 表达式时转义单引号和双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22105510/
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
Handlebars specific - escape both single and double quotes when passing Handlebars expression
提问by Kate
HTML and Handlebars:
HTML 和把手:
onclick='shareItem("{{name}}")'>
Does not successfully pass a safely escaped name when it has double quotes in it.
当其中包含双引号时,不会成功传递安全转义的名称。
onclick="shareItem('{{name}}')">
Does not successfully pass a safely escaped name when it has single quotes in it.
当其中包含单引号时,不会成功传递安全转义的名称。
I need to handle both eventualities- and even in the same string.
我需要处理这两种情况 - 甚至在同一个字符串中。
It feels sloppy to have to define a JS variable and pass it to a backslash adder.
必须定义一个 JS 变量并将其传递给反斜杠加法器感觉很草率。
Is there a cleaner way to do this with Handlebars or Moustache?
使用 Handlebars 或 Moustache 是否有更清洁的方法来做到这一点?
回答by Seyeong Jeong
You need to register a inline helperthat manipulates the context. In your case, you need to escape a single or double quote.
您需要注册一个操作上下文的内联助手。在您的情况下,您需要转义单引号或双引号。
Handlebars.registerHelper('escape', function(variable) {
return variable.replace(/(['"])/g, '\');
});
By registering such helper, you can use it with a variable to achieve what you want.
通过注册这样的助手,您可以将它与变量一起使用来实现您想要的。
{{ escape name }} # expects to escape any ' or "
I wrote a simple example to demonstrate this on jsfiddle: http://jsfiddle.net/VLy4L/
我写了一个简单的例子来在 jsfiddle 上演示这一点:http: //jsfiddle.net/VLy4L/
回答by Mariano Agüero
I have a problem trying to escape single quotes, and I use the helper that handleblars provide, you can use triple brackets {{{ variable }}} for escape
我在尝试转义单引号时遇到问题,我使用了把手提供的帮助程序,您可以使用三方括号 {{{ 变量 }}} 进行转义