Handlebars specific - escape both single and doubl

2019-04-05 01:04发布

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?

2条回答
等我变得足够好
2楼-- · 2019-04-05 02:01

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/

查看更多
仙女界的扛把子
3楼-- · 2019-04-05 02:06

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

查看更多
登录 后发表回答