Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[discussion] Access the Context's index and length #654

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions lib/dust.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,12 +353,19 @@
* @returns {string|object}
*/
Context.prototype.get = function(path, cur) {
var first = path[0];
if (typeof path === 'string') {
if (path[0] === '.') {
if (first === '.') {
cur = true;
path = path.substr(1);
}
path = path.split('.');
} else {
switch(first) {
case '$idx':
case '$len':
return this.stack && this.stack[first];
}
}
return this._get(cur, path);
};
Expand Down Expand Up @@ -536,8 +543,13 @@
this.tail = tail;
this.isObject = head && typeof head === 'object';
this.head = head;
this.index = idx;
this.of = len;

if(idx === undefined && len === undefined) {
idx = this.tail && this.tail.index;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's this for?

len = this.tail && this.tail.of;
}
this.index = this.$idx = idx;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's too late now but I wish we exposed a getter instead of the actual value. I doubt it's a big deal but I'm not keen on the "feature" that idx and len are writable. Getting them off of the stack head is a huge improvement so 👍

this.of = this.$len = len;
}

function Stub(callback) {
Expand Down Expand Up @@ -763,7 +775,7 @@
var body = bodies.block,
skip = bodies['else'],
chunk = this,
i, len, head;
i, len;

if (typeof elem === 'function' && !dust.isTemplateFn(elem)) {
try {
Expand Down Expand Up @@ -792,14 +804,9 @@
if (body) {
len = elem.length;
if (len > 0) {
head = context.stack && context.stack.head || {};
head.$len = len;
for (i = 0; i < len; i++) {
head.$idx = i;
chunk = body(chunk, context.push(elem[i], i, len));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Speaking of smell. The params for idx and len come from here, get funneled through context.push just to be stored on stack.

}
head.$idx = undefined;
head.$len = undefined;
return chunk;
} else if (skip) {
return skip(this, context);
Expand Down