diff options
author | kpdecker <kpdecker@gmail.com> | 2014-11-26 08:02:55 -0600 |
---|---|---|
committer | kpdecker <kpdecker@gmail.com> | 2014-11-26 08:02:55 -0600 |
commit | 3a9440f954092558275cd4c05a35ba34bcbfa210 (patch) | |
tree | 4ea9484e7fc898f9d3d67ad4d7c88c7f0d2b1922 /lib/handlebars/base.js | |
parent | e4c874d1afe48cc77138acf7d3ee15261e27f6e4 (diff) | |
download | handlebars.js-3a9440f954092558275cd4c05a35ba34bcbfa210.zip handlebars.js-3a9440f954092558275cd4c05a35ba34bcbfa210.tar.gz handlebars.js-3a9440f954092558275cd4c05a35ba34bcbfa210.tar.bz2 |
Make each helper data uniform
Provide @key and @last value for all forms of iteration.
Fixes #910
Diffstat (limited to 'lib/handlebars/base.js')
-rw-r--r-- | lib/handlebars/base.js | 45 |
1 files changed, 26 insertions, 19 deletions
diff --git a/lib/handlebars/base.js b/lib/handlebars/base.js index cec2937..50aa3f8 100644 --- a/lib/handlebars/base.js +++ b/lib/handlebars/base.js @@ -117,36 +117,43 @@ function registerDefaultHelpers(instance) { data = createFrame(options.data); } + function execIteration(key, i, last) { + if (data) { + data.key = key; + data.index = i; + data.first = i === 0; + data.last = !!last; + + if (contextPath) { + data.contextPath = contextPath + key; + } + } + ret = ret + fn(context[key], { data: data }); + } + if(context && typeof context === 'object') { if (isArray(context)) { for(var j = context.length; i<j; i++) { - if (data) { - data.index = i; - data.first = (i === 0); - data.last = (i === (context.length-1)); - - if (contextPath) { - data.contextPath = contextPath + i; - } - } - ret = ret + fn(context[i], { data: data }); + execIteration(i, i, i === context.length-1); } } else { + var priorKey; + for(var key in context) { if(context.hasOwnProperty(key)) { - if(data) { - data.key = key; - data.index = i; - data.first = (i === 0); - - if (contextPath) { - data.contextPath = contextPath + 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) { + execIteration(priorKey, i-1); } - ret = ret + fn(context[key], {data: data}); + priorKey = key; i++; } } + if (priorKey) { + execIteration(priorKey, i-1, true); + } } } |