【问题标题】:calling function with arguments in mustache javascript用小胡子javascript中的参数调用函数
【发布时间】:2011-05-18 13:06:27
【问题描述】:

是否可以使用Mustache.js 调用带有参数的函数

{{somefunction(somevalue)}} 谢谢

【问题讨论】:

    标签: javascript mustache


    【解决方案1】:

    https://mustache.github.io/mustache.5.html查看有关 Lambda 的部分

    小胡子模板块:

    {{#someFunction}}someValue{{/someFunction}}
    

    功能块:

    someFunction : function () {
      return function(val, render) {
        return "I passed in this value: " + render(val);
      };
    }
    

    输出:

    I passed in this value: someValue
    

    【讨论】:

    • 只是一个javascript警告,在返回函数块之后,需要有一个分号(;)。 Sublime Text 的 SublimeLinter 包选择了这个。
    • 这只有在我将函数签名更改为return function(val, render) {时才对我有用
    • 注意 someValue 是一个文本块,它不会被扩展,所以使用 {{#someFunction}}{{somevalue}}{{/someFunction}},函数将传递字符串“{{some value}}”的值。这可能是一个更可能的用例,例如用于格式化日期或货币等
    • @JamesWestgate render 函数的意图不是将原始字符串值val 转换为扩展形式吗?
    【解决方案2】:

    对我来说这是可行的:

    将通用函数FUNC添加到json(数据)中:

     data.FUNC = function(){
                    return function(val, render){
                        var values = JSON.parse(render(val));
                        return window[values.FUNCNAME].apply(this, values.FUNCARGS);
                    };
                };
    

    页面上的常规 javascript:

     function foo(arg1, arg2){
        return "Arg1 is " + arg1 +  " and Arg2 is " + arg2;
    };
    

    Mustache 模板块以标记值作为参数调用常规 javascript 函数:

    {{#FUNC}}{"FUNCNAME":"foo", "FUNCARGS":["{{page}}","{{title}}"]}{{/FUNC}}
    

    你也可以调用json中定义的函数:

    {{#calljsfunction}} {{#FUNC}}{"FUNCNAME":"{{calljsfunction}}", "FUNCARGS":["{{page}}","{{title}}"]}{{/FUNC}}{{/calljsfunction}}

    【讨论】:

      【解决方案3】:

      如果您希望在将标记插入 nito dom 后执行脚本内容,您应该使用一些类似 jquery 的库。

      在这里试试这个:

      http://jsfiddle.net/anilkamath87/GBP8N/

      此外,如果您想在脚本文件中调用其他方法。您需要做的就是根据该函数的范围以及它是否已预加载到 dom 中来调用该函数。

      希望这会有所帮助。

      P.S:注意模板标记中脚本标签的转义

      【讨论】:

      • Mustache 的想法是您将 javascript 保留在模板之外,并使用 Mustache 提供的模板标签插入它。
      【解决方案4】:

      一点解决方法,您可以将值存储在元素的 id 中

      <button id="{{value}}" onclick="somefunction(id)">Click</button>
      
      <script>    
      function somefunction(value){
                  
      }  
      </script>
      

      【讨论】:

        【解决方案5】:

        当我从 API 发送模板数据时,对 JSON 中的函数进行编码是混乱的,所以我创建了一个简单的函数来解析带有来自 API 响应的参数的任意函数,以调用现有的 JS 函数。 下面的 cmets 解释了功能。

        TLDR;函数解析

            $.each(funcs, function (funcName, args) {
                window[funcName].apply(null, args);
            });
        

        使用它的上下文。

        api 响应数据

        {
            "templatesList": [
                {
                    "load_sites": {  // the template key - see load_templates()
                        "target": "#main",  // the target css selector
                        "append": false,        // whether to append to, or set content of css selector
                        "data": {               // mustache template data
                            "sites": [
                                {
                                    "siteID": "1",
                                    "siteName": "Mr Bean House",
                                },
                                {
                                    "siteID": "2",
                                    "siteName": "Bob the Builder House",
                                }
                            ]
                        },
                        "funcs": {   // function to call after template insertion
                            "sites_load": [1, 2]   // function sites_load(1,2);
                        }
                    }
                }
            ]
        }
        

        api reposnse 解析器函数 (main.js)

        $.each(apiResponse.templatesList, function (ti, templateObject) {   // multiple responses in any API response
            $.each(templateObject, function (templateKey, template) {           // break up each into more readable chunks
                render_template( template.target, templateKey, template.data, template.append, template.funcs );  // call the renderer function
            });
        });
        

        渲染器函数 (main.js)

        function render_template(target, templateKey, templateData, append, funcs) {
            if (typeof templates_html[templateKey] !== "undefined") {  // see function load_templates()
                if (append) {  // append template
                    $(target).append( Mustache.to_html( templates_html[templateKey], templateData ) );
                } else {  // set template as content
                    $(target).html( Mustache.to_html( templates_html[templateKey], templateData ) );
                }
                
                // parse functions
                if(funcs){
                    $.each(funcs, function (funcName, args) {
                        window[funcName].apply(null, args);
                    });
                }
            }
        }
        

        要通过 API 响应调用的 js 函数 (main.js)

        function sites_load(loadJobs, loadProgress){
            console.log("load jobs for site", loadJobs);
            console.log("load progress for site", loadProgress);
        }
        

        模板加载器 - 在页面加载时加载模板 html (main.js)

        // global
        templates_html = {};
        
        // load templates html file using the <script id> for the object keys
        function load_templates() {
            templates_html = {};
            $.get("templates.html", function (templates) {
                $(templates).filter("script").each(function (templateIndex, templateHTML) {
                    var id = $(templateHTML).attr("id");  // id from script tag
                    templates_html[id] = $(th).html(); // assign html content to object key
                });
            });
        }
        

        示例模板 (templates.html)

        <script id="load_sites" type="text/html">
            {{#sites}}
                <div data-siteid="{{siteID}}">
                    {{siteName}}</small>
                </div>
            {{/sites}}
        </script>
        

        【讨论】:

          【解决方案6】:

          您是否尝试调用函数作为解析小胡子代码的一部分?或生成输出,这将调用 JavaScript 函数?例如这将输出调用该函数的 HTML(我相信)。

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

          【讨论】:

          • 在我的情况下,我有这个,即:

            {{something}}

            ,就像这样:var something=function(){return "a"};当我渲染模板时,它的调用变量是一个函数......所以我用“a”代替{{something}}......但现在我需要参数,这就是我正在搜索的内容
          • 如果您要在任何地方插入&lt;script&gt; 标签,只需使用默认的underscore templates 而不是logic-less 小胡子模板。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多