特定的句柄 - 在传递Handlebars表达式时,可以转义单引号和双引号 [英] Handlebars specific - escape both single and double quotes when passing Handlebars expression
问题描述
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.
必须定义一个JS变量并且感觉很草率将它传递给反斜杠加法器。
It feels sloppy to have to define a JS variable and pass it to a backslash adder.
使用Handlebars或Mustache有更简洁的方法吗?
Is there a cleaner way to do this with Handlebars or Moustache?
推荐答案
您需要注册一个操纵上下文的内联帮助器。在您的情况下,您需要转义单引号或双引号。
You need to register a inline helper that manipulates the context. In your case, you need to escape a single or double quote.
Handlebars.registerHelper('escape', function(variable) {
return variable.replace(/(['"])/g, '\\$1');
});
通过注册这样的帮助,您可以将它与变量一起使用来实现您想要的效果。
By registering such helper, you can use it with a variable to achieve what you want.
{{ escape name }} # expects to escape any ' or "
我写了一个简单的例子来在jsfiddle上演示这个: http://jsfiddle.net/VLy4L/
I wrote a simple example to demonstrate this on jsfiddle: http://jsfiddle.net/VLy4L/
这篇关于特定的句柄 - 在传递Handlebars表达式时,可以转义单引号和双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!