使用 Mustache 变量标签将数组传递给 JavaScript 函数

Pass in array to JavaScript function using Mustache variable tag

我正在使用 Node.js ExpressHogan 模板,我相信它使用 Mustache变量标签。我有一个 JavaScript 数组,我正试图将其传递到 JavaScript 函数中,该函数是我的 hogan 模板的一部分。这是我正在尝试做的一个例子:

https://jsfiddle.net/z1ga8wgw/

如果你检查 JavaScript 控制台并点击那里的错误,你会注意到模板扩展成这样,这会给出一个错误:

function test([object Object],[object Object],[object Object]) {
    console.log('test');
}

我在实际应用中得到的错误是:

Uncaught SyntaxError: Unexpected identifier

JSFiddle 给出的错误是这样的:

Uncaught SyntaxError: Unexpected identifier
    at DOMEval (jquery-git.js:82)
    at domManip (jquery-git.js:5782)
    at jQuery.fn.init.append (jquery-git.js:5918)
    at HTMLDocument.<anonymous> ((index):61)
    at mightThrow (jquery-git.js:3569)
    at process (jquery-git.js:3637)

我希望能够将一个数组作为参数,但如您所见,参数的数量可能会有所不同。如果没有错误,我也会接受这种类型的行为,因为我相信您可以使用 arguments 变量,但如果可能的话,最好只使用一个参数。


编辑

这是来自 JSFiddle 的测试代码(它也有 Mustache 和 JQuery 作为我没有在这里列出的资源):

HTML

<div id="output"></div>

<script type="text/html" id="test">
    <script>
    function test({{data}}) {
        console.log('test');
    }
    </script>
</script>

JavaScript:

// Got help with this template from: http://jsfiddle.net/evildonald/hqAnK/
$(document).ready(function () {
    var output = $("#output");    
    var template = $("#test").html();

    var data = { data : [
        {value : "1", text : "text 1"},
        {value : "2", text : "text 2"},
        {value : "3", text : "text 3"}
    ]};

    html = Mustache.render(template, data);
    output.append(html);
});

Mustach 行为正确,您尝试执行的操作是不可能的。

你正在写一个函数声明,参数必须是变量名,而不是数组的字符串表示。

[
  {value : "1", text : "text 1"},
  {value : "2", text : "text 2"},
  {value : "3", text : "text 3"}
].toString()

// => [object Object],[object Object],[object Object]

如果您想在模板中检索数组,则必须使用 JSON.stringify 对其进行序列化。

Javascript

var data = { 
  data : JSON.stringify(
    [
      {value : "1", text : "text 1"},
      {value : "2", text : "text 2"},
      {value : "3", text : "text 3"}
    ]
  )
};

HTML

<script type="text/html" id="test">
  <script>
    function test(data) {
      console.log('test', data);
    }

    // call your function with data as parameter
    test( {{{data}}} );
    //    ^^^    ^^^ Use {{{}}} syntax to not escape quotes into html entities
  </script>
</script> 

https://jsfiddle.net/z1ga8wgw/1/