From 81ab590d95d9322d54cdd1eb8135bbc644d14d51 Mon Sep 17 00:00:00 2001 From: Jimmy Chan Date: Sun, 19 Jan 2014 11:27:21 -0800 Subject: [PATCH] Issue #407, compileFn does not require a name. Add unit test as well --- lib/compiler.js | 9 +++++---- lib/dust.js | 6 ++++-- test/core.js | 15 +++++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/lib/compiler.js b/lib/compiler.js index aacf61e8..61b6c524 100644 --- a/lib/compiler.js +++ b/lib/compiler.js @@ -13,10 +13,11 @@ compiler.compile = function(source, name) { - // if compile is called from compileFn via renderSource, name parameter can be ignored, - // as the templates will be rendered immediately and need not be stored in cache, but if - // compile is called directly, the template will be cached with its name, so name is mandatory. - // Only renderSource passes null as name + // the name parameter is optional. + // this can happen for templates that are rendered immediately (renderSource which calls compileFn) or + // for templates that are compiled as a callable (compileFn) + // + // for the common case (using compile and render) a name is required so that templates will be cached by name and rendered later, by name. if (!name && name !== null) { dust.log(new Error("Template name parameter cannot be undefined when calling dust.compile"), 'ERROR'); } diff --git a/lib/dust.js b/lib/dust.js index a3f4ab6f..1f64ebfb 100644 --- a/lib/dust.js +++ b/lib/dust.js @@ -101,11 +101,13 @@ }; dust.renderSource = function(source, context, callback) { - //passing null, so that 'compile' knows that template has to be compiled but not to be stored in cache - return dust.compileFn(source, null)(context, callback); + return dust.compileFn(source)(context, callback); }; dust.compileFn = function(source, name) { + // name is optional. When name is not provided the template can only be rendered using the callable returned by this function. + // If a name is provided the compiled template can also be rendered by name. + name = name || null; var tmpl = dust.loadSource(dust.compile(source, name)); return function(context, callback) { var master = callback ? new Stub(callback) : new Stream(); diff --git a/test/core.js b/test/core.js index 79e13b3e..488519a0 100644 --- a/test/core.js +++ b/test/core.js @@ -49,6 +49,21 @@ exports.coreSetup = function(suite, auto) { }); }); + suite.test("compileFn", function() { + var unit = this, + tmpl = dust.compileFn('Hello World'); + tmpl({}, function(err, out) { + try { + unit.ifError(err); + unit.equals(out, "Hello World"); + } catch(err) { + unit.fail(err); + return; + } + unit.pass(); + }); + }); + suite.test("renderSource (stream)", function() { var unit = this; dust.renderSource('Hello World', {}).on('data', function(data) {