• Handlebars
  • Tutorial


Down below I have a Handlebars template that displays the firstName property of a context object. In this case, it's the person object up above, with a property of firstName and a value of Joe. When I call the template method with the person object, I get back a string of HTML that I can then append to the body of the page.

But what if I want to call a method inside of my template. For example, instead of just displaying the first name, I might want to display a greeting, or call a method called displayName. So let's get rid of this firstName expression and change it with displayName, which we'll define in a second. We can define these methods like displayName as global helpers, by calling the Handlebars.registerHelper method.

The first parameter would be the name of the method. And the second a function that can take any number of parameters. This function will just return the person's first name and the last name separated by a space. And since we don't have a last name property defined in the person object yet, let's go ahead and define one.

And finally, we'll pass the person object as a parameter to the displayName method. This is the current context object, which is our person object that we defined above. When we pass that person object in as a parameter to the template function it becomes the context object which we can then refer to with this.

And this gets passed as the person object to the displayName method. And then we can call the firstName and lastName properties of the person object. And over in the browser, we can see our displayName global helper working properly. We can pass multiple parameters to Handlebars helper. Let's say we wanted to display a greeting. So as the second parameter, I'll pass Hello as the greeting.

Up in the Helper function, I'll add a parameter and I'll call it Greeting. And then in front of the person's first name I'll add the Greeting. And just in case no greeting is passed in, I'll give it a default value of Hello.

And over in the browser, we see that it works. Two things I'd like to point out. First, is that parameters are separated by spaces in the Handlebars expression. And second, you can pass any number of parameters into the function just keep adding them to the end.