How to pass an object to a .handlebars template and use it in a javascript code block?

て烟熏妆下的殇ゞ 提交于 2021-02-02 09:59:16

问题


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:


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>


来源:https://stackoverflow.com/questions/64407740/how-to-pass-an-object-to-a-handlebars-template-and-use-it-in-a-javascript-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!