calling function with arguments in mustache javascript
Solution 1:
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
Solution 2:
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}}
Solution 3:
If you want the script contents to be executed after the markup is inserted nito the dom you should use some library that will do the same like jquery.
Try this out here:
http://jsfiddle.net/anilkamath87/GBP8N/
Also if you want to invoke some other method in your script file. All you need to do is call the function depending on the scope of that function and if it has been preloaded into the dom.
Hope this helps.
P.S: note the escape of the script tag in the template markup