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

时间:2016-12-20 05:36:30

标签: javascript mustache

我使用 Node.js Express Hogan 模板,我认为这些模板使用 Mustache 变量标签。我有一个JavaScript数组,我试图传递给我的hogan模板的JavaScript函数。这是我想要做的一个例子:

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)

我希望能够将一个数组作为参数,但正如您所看到的,参数的数量可能会有所不同。如果没有错误,我会解决这种行为,因为我相信你可以使用参数变量,但只有一个参数最好,如果这样做的话。可能的。

修改

以下是来自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);
});

1 个答案:

答案 0 :(得分:1)

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/