2

I want to pass an entire object right into javascript, but it doesn't seem to work. I tried the {{{data}}} approach and the {{data}} approach like recommended in another post. I'm doing something like this in the handlebars file:

<script>
  var myData = {{data}}; // or even {{{data}}}
</script>

Both of these give me the exception: Uncaught SyntaxError: Unexpected Identifier. However if I do a

var myDataUrl = "{{data.url}}";

It works fine, but for the first case it prints out "[Object Object"]. Any thoughts on how I can make case 1 work?

2
  • Handlebars templates are not JavaScript. if you want to use them to produce JavaScript, you can, but you have to render them as plain text first, and then evaluate the results. Commented Oct 23, 2014 at 4:31
  • What's the best way to do that? A JSON.stringify({{{data}}}) seems to have the same issue. Commented Oct 23, 2014 at 4:37

1 Answer 1

4

To insert Javascript data directly into template, you need to make it into a legal javascript string and pass that string into the template. It needs to be legal Javscript before it gets to the template. Using something like JSON.stringify() is one such way to make legal Javascript, but it isn't the only way.

Here's a piece from a handlebars template of mine that inserts some javascript data structures into the HTML file:

<script>
// temperature data - array of arrays of the form [dateTime, atticTemp, outsideTemp]
var temperatureData = {{{temperatures}}};
// onOffData is an array of [dateTime, str] - where str is "on" or "off"
var onOffData = {{{onOffData}}};
</script>

And, the data passed to the template looks like this (the two method calls return JSON strings):

app.get('/chart', function(req, res) {
    var tempData = {
        temperatures: data.getTemperatureDataSmallJSON(),
        onOffData: data.getFanOnOffDataSmallJSON(),
        units: req.cookies.temperatureUnits
    };
    res.render('chart', tempData);
});

This results in a piece of an HTML file that looks like this:

<script>
// temperature data - array of arrays of the form [dateTime, atticTemp, outsideTemp]
var temperatureData = [[1412752013861,22.19,16.35],[1412753505591,22,16.15],[1412754286561,21.85,15.94]];
// onOffData is an array of [dateTime, str] - where str is "on" or "off"
var onOffData = [[1411786960889,"off"],[1411790853867,"off"]];
</script>

Note, I'm turning the data into JSON and passing that JSON string into the template.

Sign up to request clarification or add additional context in comments.

Comments

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.