diff --git a/lib/dust.js b/lib/dust.js index d39ec9ab..93a39417 100644 --- a/lib/dust.js +++ b/lib/dust.js @@ -267,18 +267,19 @@ }; // 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); } @@ -286,7 +287,7 @@ } // 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; }; @@ -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; } diff --git a/test/helpers/template.helper.js b/test/helpers/template.helper.js index 9e1e2361..2ae05105 100644 --- a/test/helpers/template.helper.js +++ b/test/helpers/template.helper.js @@ -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('!'); + }; })); diff --git a/test/templates/all.js b/test/templates/all.js index dbc5c054..941e40ae 100755 --- a/test/templates/all.js +++ b/test/templates/all.js @@ -1284,6 +1284,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" } ] },