calling function with arguments in mustache javascript

Is it possible to call a function with arguments with Mustache.js

{{somefunction(somevalue)}}
thank you

Answers:

Answer

Check out the section on Lambdas at http://mustache.github.com/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
Answer

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

Answer

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}}

Answer

Are you trying to call a function as part of your parsing of the mustache code? or generate output, that would call the JavaScript function? e.g. This would output HTML that would call the function (I believe).

{{#items}}
  <script>{{funcName}}("{{url}}");</script>
{{/items}}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.