November 23, 2014
Hot Topics:

Using a Handlebars.js Helper, Page 2

  • August 24, 2011
  • By Jason Gilmore
  • Send Email »
  • More Articles »

Using a Handlebars.js Helper

Handlebars.js includes a number of native helpers which allow you to use conditionals and introduce further clarity into the code. For instance, you can use the each helper to make abundantly clear what is happening in the previous template:

{{#each alphabet}}
  
    <td> </td>{{letter}}
    <td> </td>{{code}}
  
{{/each}}

Additionally, it's possible to create your own helpers. For instance, suppose you wanted to conditionally link every code found in the previous display to an audio playback widget based on availability of an audio file. Rather than muddle up the template a conditional you can maintain it within a custom helper. To begin, I've modified the object array to include information which determines whether audio is associated with the letter:

var data = { 
  alphabet: [
    {letter: "A", code: ".-", audio: 0},
    {letter: "B", code: "-...", audio: 1},
    {letter: "C", code: "-.-.", audio: 1},
    {letter: "D", code: "-..", audio: 0},
    {letter: "E", code: ".", audio: 0}
  ]
};

Next create the helper:

Handlebars.registerHelper('audio_link', function(available) {
  if (available.audio) {
    return "<a href="player.html?letter=" + available.letter + "" target="_blank">Listen</a>";
  } else {
    return "N/A";
  }
});

Finally, to take advantage of the helper you can reference it by name within the template:

...

  <td> </td>{{letter}}
  <td> </td>{{code}}
  <td> </td>{{{audio_link this}}}

...

Render the revised code to the screen and you'll see output similar to that presented in Figure 2.

Using a Handlebars.js Helper
Figure 2. Using a Handlebars.js Helper

Where to From Here?

Handlebars.js is one of several popular open source JavaScript templating solutions. Consider checking out Mustache, which is actually the inspiration for (and template-compatible with) Handlebars.js. Additionally, if you'd rather keep as much as possible within the jQuery family, check out the official jQuery Templates plugin.

About the Author

Jason Gilmore -- Contributing Editor, PHP -- is the founder of EasyPHPWebsites.com, and author of the popular book, "Easy PHP Websites with the Zend Framework". Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer's conference, and was a member of the 2008 MySQL Conference speaker selection board.


Tags: JavaScript, Template engine

Originally published on http://www.developer.com.

Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel