Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...