Bläddra i källkod

feat: Allows to register global "Functions" to access from the Mustache instance

pull/800/head
jrafa1994@gmail.com 3 år sedan
förälder
incheckning
d7713f6517
1 ändrade filer med 22 tillägg och 1 borttagningar
  1. +22
    -1
      mustache.js

+ 22
- 1
mustache.js Visa fil

@@ -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.


Laddar…
Avbryt
Spara