Last active
April 21, 2021 09:08
-
-
Save TastyToast/5053642 to your computer and use it in GitHub Desktop.
Truncate helper for Handlebars.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Handlebars.registerHelper ('truncate', function (str, len) { | |
if (str.length > len) { | |
var new_str = str.substr (0, len+1); | |
while (new_str.length) { | |
var ch = new_str.substr ( -1 ); | |
new_str = new_str.substr ( 0, -1 ); | |
if (ch == ' ') { | |
break; | |
} | |
} | |
if ( new_str == '' ) { | |
new_str = str.substr ( 0, len ); | |
} | |
return new Handlebars.SafeString ( new_str +'...' ); | |
} | |
return str; | |
}); |
That's really useful. Thanks for sharing!
Thanks for sharing.
Thanks for sharing - one thing, just add a check for str bc if there's no string you'll get an exception thrown...
if (str && str.length > len) { ...
Thanks for sharing!
thanks for sharing this worked
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found it useful to make the truncation respect full words. Here is a revised version that does just that. If there is only one word, then it will truncate the middle of that word.