Почему усы не работают с данными JSON - PullRequest
0 голосов
/ 20 июня 2019

Я пытаюсь использовать 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 голосов
/ 14 июля 2019
<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);
...