Passing a function into a Handlebars template

后端 未结 2 638
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 06:04

I\'m using (or at least starting with) HandlebarsJS for the html templates but I might have hit a dead end. What I want is to pass a function to the template, e.g.



        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 06:18

    The solution is pretty straightforward.

    Handlebars will output the properties of the object you're passing into the templates, if the property is a function, it will execute the function and output the returned value

    In your example the function doesn't return any value (it just calls alert), so the output is empty.

    You could create an helper method like this:

    handlebars.registerHelper('stringifyFunc', function(fn) {
        return new Handlebars.SafeString("(" + 
                   fn.toString().replace(/\"/g,"'") + ")()");
    });
    

    Then from within the template you just need to use it on the function that needs to be stringified:

    {{text}}

提交回复
热议问题