The substring Helper for Handlebar Templates

Handlebars provide a very simple and sleek solution for microtemplating. You may like the simplicity of Handlebars for the first time. But with time your requirements may grow up and the simplicity may convert into pain as you will not be finding the common utility functions in Handlebars. In this article I have shown how to create a simple Handlebar helper for "substring". We will see how we can pass parameters to the helper functions in Handlebars.


Suppose you want to print a long string that should not output more than 50 characters. Here is the example template:
<div class="info">
 <span class="title">{{title}}</span>
 <span class="description">{{description}}</span>
</div>
And the context is:
{
  title: "This is a long title",
  body: "And this description is very long. This does not fit in our HTML container. We may have to trim it :("
}

Register a Helper

This JavaScript code should be placed in any of your javascript file that is called before the template rendering.
Handlebars.registerHelper('substr', function(length, context, options) {
 if ( context.length > length ) {
  return context.substring(0, length) + "...";
 } else {
  return context;
 }
});

Using the Helper

<div class="info">
 {{! name of helper and the length of string to be displayed }}
 <span class="title">{{substr "20" title}}</span>
 <span class="description">{{substr "100" description}}</span>
</div>
It will result in:
It will result in:
<div class="info">
 <span class="title">This is a long title</span>
 <span class="description">And this description is very long. This does not fit in our HTML container. We may have to...</span>
</div>

We would love to hear from you...

back to top