Created
July 26, 2015 11:15
-
-
Save denyskoch/8cb294c81ea39c878dd4 to your computer and use it in GitHub Desktop.
Handlebars block helper for filtering arrays by a path.
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
function filterHelper(context, options) { | |
if (!options || !options.hash.where) { | |
throw new Exception('Must pass <where> and <is> | <isnot> to #filter'); | |
} | |
if (Handlebars.Utils.isFunction(context)) { | |
context = context.call(this); | |
} | |
if (options.data) { | |
var data = Handlebars.createFrame(options.data); | |
} | |
var newContext = context; | |
var skiped = 0; | |
var included = 0; | |
var path = options.hash.where.split('.'); | |
var pathLength = path.length; | |
if (Handlebars.Utils.isArray(context)) { | |
newContext = context.filter(function(obj){ | |
var current = obj; | |
for (var i = 0; i < pathLength; i++) { | |
if (current[path[i]] == undefined) { | |
current = undefined; | |
} | |
current = current[path[i]]; | |
} | |
included++; | |
if (options.hash.maxSkip && skiped >= options.hash.maxSkip) { | |
return true; | |
} | |
if (options.hash.max && included > options.hash.max) { | |
return false; | |
} | |
if (current == options.hash.is) { | |
if (current == options.hash.is) { | |
return true; | |
} | |
} | |
else if (options.hash.isnot) { | |
if (current != undefined && current != options.hash.isnot) { | |
return true; | |
} | |
} | |
included--; | |
skiped++; | |
return false; | |
}); | |
} | |
else { | |
throw new Exception('Must pass array to #filter'); | |
} | |
if (options.hash.as) | |
data[options.hash.as] = newContext | |
return options.fn(newContext[0], {data: data}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment