Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling function with arguments in mustache javascript

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

 {{somefunction(somevalue)}} 
thank you
like image 776
sinisa Avatar asked May 18 '11 13:05

sinisa


People also ask

How does mustache JS work?

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.

What is mustache like syntax?

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


2 Answers

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 
like image 94
bluehazetech Avatar answered Sep 30 '22 13:09

bluehazetech


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

like image 38
Holle Avatar answered Sep 30 '22 13:09

Holle