3

server.js:

app.get('/home', function (req, res) {
      data['one'] = "first";
      data['two'] = "secound";
      res.render('home', { data });
});

home.handlebars:

<script type="text/javascript">
      var data = { {{{data}}} };
      console.log(data.one);
</script>

Browser Console Error: Uncaught SyntaxError: missing ] in computed property name

How can I pass the object to use it in .handlebars template within a script code block?

76484
  • 8,498
  • 3
  • 19
  • 30
Mq77
  • 39
  • 1
  • 5

1 Answers1

3

I think there a few things we need to review in order to arrive at a solution.

First, we must understand what the triple-mustache tag means in Handlebars. By default, Handlebars will HTML-escape its output. This is a best practice for preventing Cross-Site Scripting (XSS). This means that with input { data: "<p>Hello, World!</p>" }, a Handlebars template {{ data }} will output:

&lt;p&gt;Hello, World!&lt;/p&gt;

There are some situations in which one does not want Handlebars to HTML-escape its output, and for this Handlebars offers the triple-mustache tag, which will output the unescaped HTML. For the same input and template above, the output would be:

<p>Hello, World!</p>

Second, we must understand what Handlebars does when given a JavaScript object as the expression between the double- (or triple-) curly braces to evaluate. Handlebars is essentially replacing the expression with the stringified evaluation of that expression - it's what you would get if you logged data.toString() in your console. For an object, the stringified value will be something like [object Object]. See this answer for a discussion.

For our problem, we must figure out how we can get Handlebars to render our entire data object and do so in a format that is valid JavaScript. Since Handlebars will render a String, we could pass it a stringified JSON object and use the triple-mustache to ensure that our quotes are not escaped.

Our route handler becomes:

res.render('home', { data: JSON.stringify(data) });

And our template becomes:

<script type="text/javascript">
    var data = {{{ data }}};
    console.log(data.one);
</script>
76484
  • 8,498
  • 3
  • 19
  • 30
  • 1
    You still must html-escape the output, even if the rules inside a ` – Bergi Oct 19 '20 at 01:16