calling function with arguments in mustache javascript

人走茶凉 提交于 2019-11-26 20:51:16

问题


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

{{somefunction(somevalue)}}
thank you

回答1:


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



回答2:


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




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/6045165/calling-function-with-arguments-in-mustache-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!