From d7713f6517035903ba60e597411739a4897c3b95 Mon Sep 17 00:00:00 2001 From: "jrafa1994@gmail.com" Date: Fri, 8 Jul 2022 16:25:09 -0600 Subject: [PATCH] feat: Allows to register global "Functions" to access from the Mustache instance --- mustache.js | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/mustache.js b/mustache.js index ed0cd6d..5327e81 100644 --- a/mustache.js +++ b/mustache.js @@ -703,6 +703,7 @@ var mustache = { Scanner: undefined, Context: undefined, Writer: undefined, + globalFunctions: {}, /** * Allows a user to override the default caching strategy, by providing an * object with set, get and clear methods. This can also be used to disable @@ -749,7 +750,27 @@ mustache.render = function render (template, view, partials, config) { 'argument for mustache#render(template, view, partials)'); } - return defaultWriter.render(template, view, partials, config); + return defaultWriter.render(template, Object.assign({}, mustache.globalFunctions, view), partials, config); +}; + +mustache.registerFunction = function registerFunction (name, fn) { + if (typeStr(name) !== 'string') { + throw new TypeError('String expected on first argument to mustache.registerFunction'); + } + + if (!isFunction(fn)){ + throw new TypeError('Function expected on second argument to mustache.registerFunction'); + } + + if (hasProperty(mustache.globalFunctions, name)){ + console.warn('Function "' + name + '" is already registered, it will be overridden'); + } + + mustache.globalFunctions[name] = function globalFunction () { + return function run (text, render) { + return fn.call(null, render(text)); + }; + }; }; // Export the escaping function so that the user may override it.