Created
September 23, 2014 07:45
-
-
Save burtyish/e56b396335daee06acbb to your computer and use it in GitHub Desktop.
A Handlebars.js helper that stringifies an array into readable form.
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
define [ | |
'hbs/handlebars' | |
'underscore' | |
], (Handlebars, _) -> | |
""" | |
Breaks down an array into a comma-delimited list and 'and' before the last item. | |
Options: | |
total_count - If this is a number greater than the length of array, the difference will be added as 'and x others'. | |
first_item - this item will be inserted at the beginning of the array. | |
Examples: | |
listify([x,y,z], 30, a) -> "a, x, y, z and 26 others" | |
listify([x,y], 2) -> "x and y" | |
""" | |
Handlebars.registerHelper "listify", (array, options) -> | |
list = array | |
_.defaults options.hash, | |
first_item: null | |
total_count: null | |
# insert first_item if it is defined | |
list.unshift options.hash["first_item"] if options.hash["first_item"]? and _.isString(options.hash["first_item"]) | |
if list.length < 2 | |
return "#{list}" | |
# 2 items or more | |
if _.isNumber(options.hash["total_count"]) and options.hash["total_count"] > list.length | |
last_item = "#{options.hash["total_count"] - list.length} others" | |
else | |
last_item = list.pop() | |
str = list.join ', ' | |
str = "#{str} and #{last_item}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment