Skip to content

Instantly share code, notes, and snippets.

@image72
Last active November 2, 2016 06:56
Show Gist options
  • Select an option

  • Save image72/60ef490d871cda2222ed00946b77c390 to your computer and use it in GitHub Desktop.

Select an option

Save image72/60ef490d871cda2222ed00946b77c390 to your computer and use it in GitHub Desktop.
handlebars helper repeat. with data slice
// 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