Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 488
Kate Avatar asked Feb 28 '14 20:02

Kate


People also ask

How do you escape handlebars?

Escaping Handlebars expressions Handlebars content may be escaped in one of two ways, inline escapes or raw block helpers. Inline escapes created by prefixing a mustache block with \ .

What is the escape sequence for a single quote?

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

What does variable triple brace meaning in handlebars?

Because it was originally designed to generate HTML, Handlebars escapes values returned by a {{expression}} . If you don't want Handlebars to escape a value, use the "triple-stash", {{{ . Source: https://handlebarsjs.com/guide/#html-escaping.


2 Answers

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/

like image 196
Seyeong Jeong Avatar answered Sep 20 '22 03:09

Seyeong Jeong


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

like image 41
Mariano Agüero Avatar answered Sep 24 '22 03:09

Mariano Agüero