How do I add console.log() JavaScript logic inside of a Handlebars template?

Jason Biondo picture Jason Biondo · Jul 6, 2013 · Viewed 37.6k times · Source

I'm in the process of building a new Meteor app and I can't figure out how to add JavaScript logic with Handlebars to run a console.log() before my each loop. In backbone I would just do, <% console.log(data); %> to test that the data was being passed in.
I'm not sure how to do this with Meteor and Handlebars and I couldn't find the solution on their site.

Answer

Geoffrey Booth picture Geoffrey Booth · Jul 6, 2013

Create a Handlebars helper in one of the client-loaded JavaScript files in your project:

Template.registerHelper("log", function(something) {
  console.log(something);
});

And then call it in your template:

{{log someVariable}}

You can log the current context with simply {{log this}}.

(Note that in Meteor before version 0.8, or in pure Handlebars outside of a Meteor app, replace Template.registerHelper with Handlebars.registerHelper.)