Handlebars specific - escape both single and double quotes when passing Handlebars expression

扶醉桌前 提交于 2019-12-03 15:44:28

问题


HTML and Handlebars:

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.

Is there a cleaner way to do this with Handlebars or Moustache?


回答1:


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 "

I wrote a simple example to demonstrate this on jsfiddle: http://jsfiddle.net/VLy4L/




回答2:


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



来源:https://stackoverflow.com/questions/22105510/handlebars-specific-escape-both-single-and-double-quotes-when-passing-handleba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!