Slyper
Slyper

Reputation: 906

Mustache not rendering JSON data

So, I have just started with Mustache JS. I have this simple html file

<!DOCTYPE html>
<html lang="en">
<head>
    <title>JavaScript Mustache template</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
</head>

<body>
    <script id="mp_template" type="text/template">
        <p>Country: {{ name }}</p>
        <p>Capital: {{ capital }}</p>
        <p>Flag: <img src={{{ flag }}} ></p>
    </script>
    <div id="mypanel"></div>
    <button id="btn">Load</button>
    <script>
        $(function () {
            $("#btn").on('click', function () {
                $.getJSON('https://restcountries.eu/rest/v2/name/aruba?fullText=true', function (data) {
                    var template = $("#mp_template").html();
                    var text = Mustache.render(template, data);
                    console.log(data);
                    $("#mypanel").html(text);
                });
            });
        });
    </script>

Its getting some data back via the .getJSON call and then trying to render that data on button click. No data is rendering. Can someone please advise what am I doing wrong ?

Please see this URL to see the structure of returned data https://restcountries.eu/rest/v2/name/aruba?fullText=true

Upvotes: 1

Views: 1799

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

That API returns a JSON array, not an object, that's why it isn't working.

If you only want the first item, you can do:

 var template = $("#mp_template").html();
 var text = Mustache.render(template, data[0]);
 console.log(data);
 $("#mypanel").html(text);

Or you can iterate through all the countries, by passing the array in an object property: { countries: data } and use {{#countries}} in your template

$(function () {
    $("#btn").on('click', function () {
        $.getJSON('https://restcountries.eu/rest/v2/name/aruba?fullText=true', function (data) {
            var template = $("#mp_template").html();
            var text = Mustache.render(template, { countries: data });
            $("#mypanel").html(text);
        });
    });
});
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
</head>

<body>
    <script id="mp_template" type="text/template">
      {{#countries}}
        <p>Country: {{ name }}</p>
        <p>Capital: {{ capital }}</p>
        <p>Flag: <img src={{{ flag }}} style="width: 50px"></p>
      {{/countries}}
    </script>
    <div id="mypanel"></div>
    <button id="btn">Load</button>
</body>

Upvotes: 1

Related Questions