From a3f4339c655cdfdb3f16a0a539b0b47c639db264 Mon Sep 17 00:00:00 2001 From: Phillip Johnsen Date: Wed, 24 Jun 2015 19:41:54 +0200 Subject: [PATCH] Throw error when providing .render() with invalid template type. As we require the template to be a `string` we now throw an error when given any other data type. This should provide the developers with a meaningful error rather than a cryptic TypeError from the murky depths of our source code. Fixes #464 --- mustache.js | 14 ++++++++++++++ test/render-test-browser-tmpl.mustache | 6 ++++++ test/render-test.js | 8 ++++++++ 3 files changed, 28 insertions(+) diff --git a/mustache.js b/mustache.js index ecd2b86..245c129 100644 --- a/mustache.js +++ b/mustache.js @@ -25,6 +25,14 @@ return typeof object === 'function'; } + /** + * More correct typeof string handling array + * which normally returns typeof 'object' + */ + function typeStr (obj) { + return isArray(obj) ? 'array' : typeof obj; + } + function escapeRegExp (string) { return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); } @@ -584,6 +592,12 @@ * default writer. */ mustache.render = function render (template, view, partials) { + if (typeof template !== 'string') { + throw new TypeError('Invalid template! Template should be a "string" ' + + 'but "' + typeStr(template) + '" was given as the first ' + + 'argument for mustache#render(template, view, partials)'); + } + return defaultWriter.render(template, view, partials); }; diff --git a/test/render-test-browser-tmpl.mustache b/test/render-test-browser-tmpl.mustache index 2f2917c..bf6a0e3 100644 --- a/test/render-test-browser-tmpl.mustache +++ b/test/render-test-browser-tmpl.mustache @@ -5,6 +5,12 @@ describe('Mustache.render', function () { Mustache.clearCache(); }); + it('requires template to be a string', function () { + assert.throws(function () { + Mustache.render(['dummy template'], ['foo', 'bar']); + }, TypeError, 'Invalid template! Template should be a "string" but "array" was given'); + }); + var i; var tests = {{{.}}}; diff --git a/test/render-test.js b/test/render-test.js index 93e3fcb..e9d61a9 100644 --- a/test/render-test.js +++ b/test/render-test.js @@ -9,6 +9,14 @@ describe('Mustache.render', function () { Mustache.clearCache(); }); + it('requires template to be a string', function () { + assert.throws(function () { + Mustache.render(['dummy template'], ['foo', 'bar']); + }, TypeError, 'Invalid template! Template should be a "string" but ' + + '"array" was given as the first argument ' + + 'for mustache#render(template, view, partials)'); + }); + tests.forEach(function (test) { var view = eval(test.view);