user2763557
user2763557

Reputation: 439

After passing object to handlebars, how can I access that object in script tag?

I first get the data from sql then pass it into handlebars.

Inside the tag in .handlebars/using view.js, I want to access doctors, but i keep getting[object][object]. I tried json.stringifying it before but still no luck. What is the best way to do this?

umd.matchDocs(val2, function(data) {
  console.log(data);
  var renderDocs = {
    doctors: data
  }
  res.render("dashboard", renderDocs);
});

Upvotes: 0

Views: 2034

Answers (1)

jfriend00
jfriend00

Reputation: 707916

After passing object to handlebars, how can I access that object in script tag?

No, not by default. But you can make the data available manually if you want.

Data you pass to handlebars rendering operation is available during the rendering operation only. If you want to be able to access some of that data later in client-side <script> tags, then you can "render" Javascript variables into the <script> tags that contain the desired data.

Remember when rendering data into Javascript variables, you need to render the actual Javascript text (converting to JSON will often create the text for you).

In your specific example, you could do something like this in your rendering code:

umd.matchDocs(val2, function(data) {
  console.log(data);
  var renderDocs = {
    doctors: JSON.stringify(data)
  }
  res.render("dashboard", renderDocs);
});

And, then in the template:

<script>
var doctors = {{{doctors}}};
</script>

Then, this array of doctors would be available to the Javascript in your page.

In case you haven't seen the triple braces like shown above, that's to tell handlebars to skip any HTML escaping in the data (because this isn't HTML).

Upvotes: 4

Related Questions