为什么小胡子不能使用JSON数据

时间:2019-06-20 15:30:58

标签: mustache

我正在尝试使用json填充胡须模板,但无法正常工作。请参见示例:http://jsfiddle.net/zx1kj4ey/2/

HTML

<div id="output"></div>
<script type="text/html" id="test1">
   <p>{{#Sales}}{{Product}}{{/Sales}}</p>
</script>

JavaScript

$(document).ready(function () {
   var output = $("#output");    
   var template = $("#test1").html(); 

   data1 = "{\"Sales\":[{\"Product\":\"Produto 0\",\"Qtd\":0,\"Price\":0.0},{\"Product\":\"Produto 1\",\"Qtd\":1,\"Price\":10.0}]}"

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

1 个答案:

答案 0 :(得分:0)

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

// change the script's type so Mustache recognizes it.
<script type="x-tmpl-mustache" id="test1">
    <p>
        {{#Sales}}
            {{Product}}
        {{/Sales}}
    </p>
</script>

// set the data before other stuff and parse it to an object.
var data1 = JSON.parse("{\"Sales\":[{\"Product\":\"Produto 0\",\"Qtd\":0,
    \"Price\":0.0},{\"Product\":\"Produto 1\",\"Qtd\":1,\"Price\":10.0}]}");

var template = $("#test1").html();
// tell Mustache to parse the template.
Mustache.parse(template);
var rendered = Mustache.render(template, data1);
$("#output").html(rendered);