diff --git a/lib/handlebars.js b/lib/handlebars.js index 7d85c2610..f82ec3bad 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -21,6 +21,17 @@ Handlebars.create = create; module.exports = Handlebars; // instantiate an instance +// Publish a Node.js require() handler for .handlebars and .hbs files +if (require.extensions) { + var extension = function(module, filename) { + var fs = require("fs"); + var templateString = fs.readFileSync(filename, "utf8"); + module.exports = Handlebars.compile(templateString); + }; + require.extensions[".handlebars"] = extension; + require.extensions[".hbs"] = extension; +} + // BEGIN(BROWSER) // END(BROWSER) diff --git a/spec/example_1.handlebars b/spec/example_1.handlebars new file mode 100644 index 000000000..054e96cb8 --- /dev/null +++ b/spec/example_1.handlebars @@ -0,0 +1 @@ +{{foo}} diff --git a/spec/example_2.hbs b/spec/example_2.hbs new file mode 100644 index 000000000..963eab972 --- /dev/null +++ b/spec/example_2.hbs @@ -0,0 +1 @@ +Hello, {{name}}! diff --git a/spec/qunit_spec.js b/spec/qunit_spec.js index e2f7d47d0..fef5166bc 100644 --- a/spec/qunit_spec.js +++ b/spec/qunit_spec.js @@ -1502,3 +1502,27 @@ test('isEmpty', function() { equal(Handlebars.Utils.isEmpty('foo'), false); equal(Handlebars.Utils.isEmpty({bar: 1}), false); }); + +if (typeof(require) !== 'undefined') { + suite('Require'); + + test('Load .handlebars files with require()', function() { + var template = require("./example_1"); + assert.deepEqual(template, require("./example_1.handlebars")); + + var expected = 'foo\n'; + var result = template({foo: "foo"}); + + equal(result, expected); + }); + + test('Load .hbs files with require()', function() { + var template = require("./example_2"); + assert.deepEqual(template, require("./example_2.hbs")); + + var expected = 'Hello, World!\n'; + var result = template({name: "World"}); + + equal(result, expected); + }); +}