Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 870
Jason Biondo Avatar asked Jul 06 '13 04:07

Jason Biondo


People also ask

Can you console log handlebars?

You need to modify the Handlebars object before logging it to the console. Stringify it and use triple curly braces.

How do you write JavaScript in handlebars?

Define the template that is packed with handlebars JavaScript syntax. Compile the template with handlebars JavaScript compile method. Provide the data context i.e. data from server-side in a form of JSON to map to the template. Insert or append the final HTML into your designated DOM location of the HTML page.

Can you use handlebars in JavaScript?

Handlebars. js is a Javascript library used to create reusable webpage templates. The templates are combination of HTML, text, and expressions. The expressions are included in the html document and surrounded by double curly braces.


1 Answers

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.)

like image 131
Geoffrey Booth Avatar answered Oct 01 '22 03:10

Geoffrey Booth