Can anyone suggest a better way to implement my template code?
var $teams = $('#info');
var template = "{{#data}}<tr><td>{{teamName}} </td><td>{{playedGames}}</td><td>{{wins}}</td><td>{{draws}}</td><td>{{losses}}</td><td>{{goalDifference}}</td><td>{{points}}</td></tr>{{/data}}";
$.ajax({
headers: {
'X-Auth-Token': '0fc841d392274cb5a26804330ac11e98'
},
type: 'GET',
dataType: 'json',
url: 'http://api.football-data.org/v1/soccerseasons/401/leagueTable',
success: function(standings) {
$teams.append(Mustache.render(template, {data:standings.standing}));
}
});
This template is pulling in information from an API to display the latest league statistics.
-
\$\begingroup\$ Welcome to Code Review! What is your template supposed to do? \$\endgroup\$SirPython– SirPython2016年01月06日 22:46:59 +00:00Commented Jan 6, 2016 at 22:46
-
\$\begingroup\$ It is pulling in information from an API to display the latest league statistics \$\endgroup\$Craig England– Craig England2016年01月07日 11:13:37 +00:00Commented Jan 7, 2016 at 11:13
1 Answer 1
I think it would be much cleaner to put your template in your markup instead of having it as that JavaScript string literal. You can do this by wrapping your template in a script block:
<script id="RowTemplate" type="x-tmpl-mustache">
<tr>
<td>{{teamName}}</td>
<td>{{playedGames}}</td>
<td>{{wins}}</td>
<td>{{draws}}</td>
<td>{{losses}}</td>
<td>{{goalDifference}}</td>
<td>{{points}}</td>
</tr>
</script>
Next, we can fetch our template HTML from the DOM:
var template = $('#RowTemplate').html();
The Mustache documentation says that we can pre-parse our template:
Mustache.parse(template);
Finally, you will have noticed that I did not include the {{#data}}
tags in my template. It seemed to me that name-spacing my data in this way was unnecessary. So my call to render looks as follows:
$teams.append(Mustache.render(template, standings.standing));
However, it looks odd to me that the data for each table row is getting individually loaded via AJAX. If it is possible to load all of the data with one AJAX call, then I would do so. My template would then look something like the following:
<script id="Template" type="x-tmpl-mustache">
{{#standings}}
<tr>
<td>{{teamName}}</td>
<td>{{playedGames}}</td>
<td>{{wins}}</td>
<td>{{draws}}</td>
<td>{{losses}}</td>
<td>{{goalDifference}}</td>
<td>{{points}}</td>
</tr>
{{/standings}}
</script>
This assumes the server response contains a standings
array of objects, where each object would correspond to a row in our table:
{
standings: [
/*...*/
]
}
Explore related questions
See similar questions with these tags.