Jesse Burcsik
Jesse Burcsik

Reputation: 367

How do I render Mustache templates with JSON with no root node

I am building a small page which calls an API using jquery's getJSON and then renders the data using a mustache template (at least that's the plan). However my JSON does not have a node root and am unable to loop through the JSONs response data using the proper mustache mechanics.

//start
file : jsonresponse.jsonp

?([{"CountryIsoAlpha3Code":"AFG","CountryName":"Afghanistan"},
{"CountryIsoAlpha3Code":"ALA","CountryName":"Åland Islands"},
{"CountryIsoAlpha3Code":"ALB","CountryName":"Albania"}])
//end

//start
file: tmpl.mustache

<option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
//end

//start
file: render.js

$.getJSON(jsonresponse.jsonp, function(data) { 
   var tpl = tmpl.mustache,
   i=data.length,
   html = '';
     while(i--){
       html = html + mustache.render(tpl, data[i]);
     }

//end

I realize this is completely wrong (in the template usage only, assume I am actually passing the data and template properly) but it does work. but what if I want to do the follow... HOW DO I DO IT!?:

//start
//file : daydreamer.mustache

<h1>This title is only awesome when it's rendered once</h1>
{{#}}  //no root node attempt at recursive templating rendering
     <option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
{{/}}

//end  

If this is unclear please let me know I know a poor question is an eye sore. I will try to edit as soon as possible. Thanks.

Upvotes: 2

Views: 1485

Answers (1)

gonchuki
gonchuki

Reputation: 4134

Depending on the pieces you control on this application/use case, you have 2 possible fixes: either modify the JSON data to include such root node, or add that root node to your data on your end.

The mustache template will need to get modified as follows for both solutions:

{{#options}}
    <option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
{{/options}}

Now you either wrap the data directly on the server or on your end, and then the getJSON call will be like this for the second solution (for the first one, replace the {options: data} wrapper with just data). I'm going with the second one assuming you can't control the server side because that API is fixed/mandated by somebody else:

$.getJSON("jsonresponse.jsonp", function(data) { 
    var tpl = tmpl.mustache,
        html = '';

    html = mustache.render(tpl, {options: data});
}

Upvotes: 5

Related Questions