4

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?

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

1 Comment

You still must html-escape the output, even if the rules inside a <script> tag are a little different

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.