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

后端 未结 2 1182
陌清茗
陌清茗 2021-02-07 05:42

HTML and Handlebars:

onclick=\'shareItem(\"{{name}}\")\'> 

Does not successfully pass a safely escaped name when it has double quotes in it

相关标签:
2条回答
  • 2021-02-07 05:46

    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

    0 讨论(0)
  • 2021-02-07 06:06

    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/

    0 讨论(0)
提交回复
热议问题