Last active
November 2, 2016 06:56
-
-
Save image72/60ef490d871cda2222ed00946b77c390 to your computer and use it in GitHub Desktop.
handlebars helper repeat. with data slice
This file contains hidden or 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
| // var _ = require('underscore'); | |
| function repeat(n, options) { | |
| /* jshint validthis: true */ | |
| var isNumber = function(n) { | |
| var type = typeof(num); | |
| if (type === 'string') { | |
| if (!num.trim()) return false; | |
| } else if (type !== 'number') { | |
| return false; | |
| } | |
| return (num - num + 1) >= 0; | |
| } | |
| var hasNumber = isNumber(n); | |
| var context = {}; | |
| var self = this; | |
| if (!hasNumber) { | |
| options = n; | |
| } | |
| if (self && self.context) { | |
| _.extend(self, self.context); | |
| } | |
| if (options.hasOwnProperty('hash')) { | |
| _.extend(options, options.hash); | |
| } | |
| if (options.count) { | |
| n = options.count; | |
| hasNumber = true; | |
| } | |
| _.extend(options, self, context); | |
| if (hasNumber) { | |
| return block(options); | |
| } else { | |
| console.log('options: ', options); | |
| return options.inverse(options); | |
| } | |
| function block(opts) { | |
| opts = opts || {}; | |
| var str = ''; | |
| var hash = opts.hash || {}; | |
| hash.start = hash.start || 0; | |
| for (var i = hash.start; i < n + hash.start; i++) { | |
| hash.index = i; | |
| hash.isFirst = i === 0; | |
| hash.isLast = i === (len - 1); | |
| str += opts.fn(opts, {data: hash}); | |
| } | |
| return str; | |
| } | |
| } | |
| function foreach(arr,options) { | |
| if(options.inverse && !arr.length) | |
| return options.inverse(this); | |
| return arr.map(function(item,index) { | |
| item.$index = index; | |
| item.$first = index === 0; | |
| item.$last = index === arr.length-1; | |
| return options.fn(item); | |
| }).join(''); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment