Is it possible to call a function with arguments with Mustache.js
{{somefunction(somevalue)}}thank you
It works by expanding tags in a template using values provided in a hash or object. You can use Mustache to render templates anywhere include client side and server side environments. Mustache doesn't rely on procedural statements, there are no if statements, else clauses, or for loops.
Mustache is described as a logic-less system because it lacks any explicit control flow statements, like if and else conditionals or for loops; however, both looping and conditional evaluation can be achieved using section tags processing lists and anonymous functions (lambdas).
Check out the section on Lambdas at https://mustache.github.io/mustache.5.html
Mustache template block:
{{#someFunction}}someValue{{/someFunction}}
Function block:
someFunction : function () { return function(val, render) { return "I passed in this value: " + render(val); }; }
Output:
I passed in this value: someValue
for me this works:
add general function FUNC to json (data):
data.FUNC = function(){ return function(val, render){ var values = JSON.parse(render(val)); return window[values.FUNCNAME].apply(this, values.FUNCARGS); }; };
regular javascript on page:
function foo(arg1, arg2){ return "Arg1 is " + arg1 + " and Arg2 is " + arg2; };
Mustache template block calling the regular javascript-function with tag-values as arguments:
{{#FUNC}}{"FUNCNAME":"foo", "FUNCARGS":["{{page}}","{{title}}"]}{{/FUNC}}
you also can call a function defined in the json:
{{#calljsfunction}} {{#FUNC}}{"FUNCNAME":"{{calljsfunction}}", "FUNCARGS":["{{page}}","{{title}}"]}{{/FUNC}}{{/calljsfunction}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With