Handlebars - substring

You're going to want to create a Handlebars helper in javascript to execute the substring code:

Handlebars.registerHelper('trimString', function(passedString) {
    var theString = passedString.substring(0,150);
    return new Handlebars.SafeString(theString)
});

Then, in your template, you'd call it like this:

<p> {{{trimString content}}} </p>

For those who work with EmberJS, here is my interpretation of a substr helper:

Ember.Handlebars.registerHelper('substr', function(property, options) {

    var str = Ember.get(this, property);
    var opts = options.hash;

    var start = opts.start || 0;
    var len = opts.max;

    var out = str.substr(start, len);

    if (str.length > len)
        out += '...';

    return new Ember.Handlebars.SafeString(out);
});

Usage examples:

{{substr description start=5 max=20}}

or

{{substr description max=20}}

Edit: a "bound" helper is even better.

Ember.Handlebars.registerBoundHelper('substr', function(value, options) {

    var opts = options.hash;

    var start = opts.start || 0;
    var len = opts.max;

    var out = value.substr(start, len);

    if (value.length > len)
        out += '...';

    return new Ember.Handlebars.SafeString(out);
});

this works also with nested properties:

{{substr view.product.description max=50}}

I am using values as options, starting value as well as ending value passed as arguments form template. Try this:

Handlebars.registerHelper('trimString', function(passedString, startstring, endstring) {
   var theString = passedString.substring( startstring, endstring );
   return new Handlebars.SafeString(theString)
});

In template:

<p>{{{trimString value 0 300}}}</p>

it'll print first 300 characters of the value. Hope this help you.


my define helper with string cut indicate

Handlebars.registerHelper('trimS', function(passedString, start, length ){
var mlength = length,preS='',tailS='';
if(start>0 && passedString.length>3){
    var preS= '...';
    mlength = length -3;
} ;
if(passedString.length>(start + length )){
    tailS = '...';
    mlength = mlength -3;
};
var theString = preS + passedString.substr(start, mlength) + tailS;
return new Handlebars.SafeString(theString);
});