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 #464tags/v2.1.3
| @@ -25,6 +25,14 @@ | |||||
| return typeof object === 'function'; | 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) { | function escapeRegExp (string) { | ||||
| return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); | return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); | ||||
| } | } | ||||
| @@ -584,6 +592,12 @@ | |||||
| * default writer. | * default writer. | ||||
| */ | */ | ||||
| mustache.render = function render (template, view, partials) { | 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); | return defaultWriter.render(template, view, partials); | ||||
| }; | }; | ||||
| @@ -5,6 +5,12 @@ describe('Mustache.render', function () { | |||||
| Mustache.clearCache(); | 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 i; | ||||
| var tests = {{{.}}}; | var tests = {{{.}}}; | ||||
| @@ -9,6 +9,14 @@ describe('Mustache.render', function () { | |||||
| Mustache.clearCache(); | 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) { | tests.forEach(function (test) { | ||||
| var view = eval(test.view); | var view = eval(test.view); | ||||