在 Mustache javascript 中调用带有参数的函数

发布于 2024-11-08 16:19:53 字数 133 浏览 5 评论 0原文

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

{{somefunction(somevalue)}}
thank you

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

{{somefunction(somevalue)}}
thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

独享拥抱 2024-11-15 16:19:53

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

Mustache 模板块:

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

功能块:

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

输出:

I passed in this value: someValue

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
迷雾森÷林ヴ 2024-11-15 16:19:53

对我来说,这是可行的:

将通用函数 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}}{{/调用js函数}}

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

寻找我们的幸福 2024-11-15 16:19:53

稍微解决一下,您可以将值存储在元素的 id 中

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

<script>    
function somefunction(value){
            
}  
</script>

A little work around, you can store the value in the element's id

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

<script>    
function somefunction(value){
            
}  
</script>
九局 2024-11-15 16:19:53

如果您希望在将标记插入 dom 后执行脚本内容,您应该使用一些像 jquery 一样执行相同操作的库。

在这里试试这个:

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

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

希望这有帮助。

PS:注意模板标记中script标签的转义

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

池予 2024-11-15 16:19:53

当我从 API 发送模板数据并使用 JSON 编码时,JSON 中的函数很混乱,因此我创建了一个简单的函数来解析带有来自 API 响应的参数的任意函数,以调用现有的 JS 函数。
下面的注释解释了该功能。

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

渲染器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
        });
    });
}

示例模板 (模板.html)

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

As I send my template data from an API vis JSON encoding a function in the JSON is messy so I created a simple function to parse out arbitary function with parameters from the API response to call existing JS functions.
The comments below explain the functionality.

The TLDR; function parsing

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

The context under which it's used.

api response data

{
    "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 parser function (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
    });
});

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

js function to be called called via API response (main.js)

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

templates loader - loads the template html on page load (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
        });
    });
}

example template (templates.html)

<script id="load_sites" type="text/html">
    {{#sites}}
        <div data-siteid="{{siteID}}">
            {{siteName}}</small>
        </div>
    {{/sites}}
</script>
花开雨落又逢春i 2024-11-15 16:19:53

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

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

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}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文