UNPKG

1.13 kBJavaScriptView Raw
1'use strict';
2
3const substring = require('stringz').substring;
4
5/* 2017-02-14
6 *
7 * FUNCTION
8 * truncate(str, length)
9 *
10 * DESCRIPTION (WHAT)
11 * Returns the first X characters in a string (unless it reaches the end
12 * of the string first, in which case it will return fewer). Returns a
13 * new string that is truncated to the given length.
14 *
15 * USE CASE (WHY)
16 * As a merchant, I want to display a card, at the bottom of
17 * my home page that highlights the most recent blog post. In the card,
18 * I want to display the blog thumbnail, title and the first 40 characters
19 * of the post's body. In order to extract the first 40 characters, I need
20 * a Handlebars helper that works like the javascript substring() function.
21 *
22 * USAGE
23 *
24 * {{lang (truncate 'blog.post.body.' 40) }}
25 */
26function helper(paper) {
27 paper.handlebars.registerHelper('truncate', function (string, length) {
28 if (typeof string !== 'string') {
29 return string;
30 }
31
32 const truncatedString = substring(string, 0, length);
33
34 return new paper.handlebars.SafeString(truncatedString);
35 });
36}
37
38module.exports = helper;