If you want to inject JavaScript data directly into a template, you must ensure that it is formatted as a valid JavaScript string and then pass this string into the template. It should already be in a correct format before reaching the template. Although using JSON.stringify()
is a common method to achieve this, there are other ways as well.
Here is an excerpt from one of my handlebars templates where I include various JavaScript data structures within the HTML document:
<script>
// temperature data - array of arrays in the format [dateTime, atticTemp, outsideTemp]
var temperatureData = {{{temperatures}}};
// onOffData consists of [dateTime, str] pairs where 'str' can be either "on" or "off"
var onOffData = {{{onOffData}}};
</script>
The data provided to the template appears as follows (the JSON strings are returned by these two function calls):
app.get('/chart', function(req, res) {
var tempData = {
temperatures: data.getTemperatureDataSmallJSON(),
onOffData: data.getFanOnOffDataSmallJSON(),
units: req.cookies.temperatureUnits
};
res.render('chart', tempData);
});
As a result, a portion of the HTML file will look similar to this:
<script>
// temperature data - array of arrays in the format [dateTime, atticTemp, outsideTemp]
var temperatureData = [[1412752013861,22.19,16.35],[1412753505591,22,16.15],[1412754286561,21.85,15.94]];
// onOffData consists of [dateTime, str] pairs where 'str' can be either "on" or "off"
var onOffData = [[1411786960889,"off"],[1411790853867,"off"]];
</script>
It's important to note that the data is converted to JSON format and then passed as a JSON string to the template.