summaryrefslogtreecommitdiffstats
path: root/lib/handlebars/helpers/each.js
diff options
context:
space:
mode:
authorkpdecker <kpdecker@gmail.com>2015-08-01 17:54:47 -0500
committerkpdecker <kpdecker@gmail.com>2015-08-01 17:54:47 -0500
commit15b55a307b4f95d4a861df8b32c3c1ddb4825414 (patch)
tree5b5b7fcf8fe8de9aa380d3ef2522be7b93c3bb27 /lib/handlebars/helpers/each.js
parent231a8d7256d24c1a0287d67d393f06faa32751e8 (diff)
downloadhandlebars.js-15b55a307b4f95d4a861df8b32c3c1ddb4825414.zip
handlebars.js-15b55a307b4f95d4a861df8b32c3c1ddb4825414.tar.gz
handlebars.js-15b55a307b4f95d4a861df8b32c3c1ddb4825414.tar.bz2
Move helpers into separate modules
Diffstat (limited to 'lib/handlebars/helpers/each.js')
-rw-r--r--lib/handlebars/helpers/each.js77
1 files changed, 77 insertions, 0 deletions
diff --git a/lib/handlebars/helpers/each.js b/lib/handlebars/helpers/each.js
new file mode 100644
index 0000000..9fc5a09
--- /dev/null
+++ b/lib/handlebars/helpers/each.js
@@ -0,0 +1,77 @@
+import {appendContextPath, blockParams, createFrame, isArray, isFunction} from '../utils';
+import Exception from '../exception';
+
+export default function(instance) {
+ instance.registerHelper('each', function(context, options) {
+ if (!options) {
+ throw new Exception('Must pass iterator to #each');
+ }
+
+ let fn = options.fn,
+ inverse = options.inverse,
+ i = 0,
+ ret = '',
+ data,
+ contextPath;
+
+ if (options.data && options.ids) {
+ contextPath = appendContextPath(options.data.contextPath, options.ids[0]) + '.';
+ }
+
+ if (isFunction(context)) { context = context.call(this); }
+
+ if (options.data) {
+ data = createFrame(options.data);
+ }
+
+ function execIteration(field, index, last) {
+ if (data) {
+ data.key = field;
+ data.index = index;
+ data.first = index === 0;
+ data.last = !!last;
+
+ if (contextPath) {
+ data.contextPath = contextPath + field;
+ }
+ }
+
+ ret = ret + fn(context[field], {
+ data: data,
+ blockParams: blockParams([context[field], field], [contextPath + field, null])
+ });
+ }
+
+ if (context && typeof context === 'object') {
+ if (isArray(context)) {
+ for (let j = context.length; i < j; i++) {
+ execIteration(i, i, i === context.length - 1);
+ }
+ } else {
+ let priorKey;
+
+ for (let key in context) {
+ if (context.hasOwnProperty(key)) {
+ // We're running the iterations one step out of sync so we can detect
+ // the last iteration without have to scan the object twice and create
+ // an itermediate keys array.
+ if (priorKey !== undefined) {
+ execIteration(priorKey, i - 1);
+ }
+ priorKey = key;
+ i++;
+ }
+ }
+ if (priorKey) {
+ execIteration(priorKey, i - 1, true);
+ }
+ }
+ }
+
+ if (i === 0) {
+ ret = inverse(this);
+ }
+
+ return ret;
+ });
+}