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:
<p>Hello, World!</p>
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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…