Skip to content

Commit

Permalink
Pass the current context to filters.
Browse files Browse the repository at this point in the history
  • Loading branch information
Seth Kinast committed Jun 2, 2015
1 parent 80eb24d commit 6c86570
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
13 changes: 7 additions & 6 deletions lib/dust.js
Expand Up @@ -267,26 +267,27 @@
};

// apply the filter chain and return the output string
dust.filter = function(string, auto, filters) {
var i, len, name;
dust.filter = function(string, auto, filters, context) {
var i, len, name, filter;
if (filters) {
for (i = 0, len = filters.length; i < len; i++) {
name = filters[i];
if (!name.length) {
continue;
}
filter = dust.filters[name];
if (name === 's') {
auto = null;
} else if (typeof dust.filters[name] === 'function') {
string = dust.filters[name](string);
} else if (typeof filter === 'function') {
string = filter(string, context);
} else {
dust.log('Invalid filter `' + name + '`', WARN);
}
}
}
// by default always apply the h filter, unless asked to unescape with |s
if (auto) {
string = dust.filters[auto](string);
string = dust.filters[auto](string, context);
}
return string;
};
Expand Down Expand Up @@ -755,7 +756,7 @@
} else if (dust.isStreamable(elem)) {
return this.stream(elem, context, null, auto, filters);
} else if (!dust.isEmpty(elem)) {
return this.write(dust.filter(elem, auto, filters));
return this.write(dust.filter(elem, auto, filters, context));
} else {
return this;
}
Expand Down
4 changes: 4 additions & 0 deletions test/helpers/template.helper.js
Expand Up @@ -24,4 +24,8 @@
}
return val;
};
dust.filters.woo = function(string, context) {
var wooLevel = parseInt(context.get('woo')) + 1;
return string.toUpperCase() + new Array(wooLevel).join('!');
};
}));
7 changes: 7 additions & 0 deletions test/templates/all.js
Expand Up @@ -1270,6 +1270,13 @@ return [
context: { obj: JSON.stringify({ id: 1, name: "bob", occupation: "construction" }) },
expected: JSON.parse(JSON.stringify({ id: 1, name: "bob", occupation: "construction" })).toString(),
message: "should objectify a JSON string when using the jp filter"
},
{
name: "filter receives context",
source: "{#dust}{name|woo}{/dust}",
context: { woo: 0, name: "Boo", dust: { woo: 5, name: "Dust" } },
expected: "DUST!!!!!",
message: "filters are passed the current context"
}
]
},
Expand Down

0 comments on commit 6c86570

Please sign in to comment.