I use mustache for templating my javascript ajax calls, Here is my data and the template:
{'joined':1} // ajax responde data json.
var myTemplate = '{{ joined }} person joined so far.'
It works, however I want to fix the grammer in this, if more than 1 person joins, I want to show 5 people joined so far
.
How to achieve this without manipulating the server side ajax json responder ?
You can add conditional logic inside the JavaScript object, if you can coax your server-side AJAX into delivering it that way:
var json = {
'joined': 1,
'ppl': function() {
return (this.joined === 1) ? 'person' : 'people'
}
} // ajax responde data json.
var myTemplate = '{{ joined }} {{ppl}} joined so far.'
Mustache.to_html(myTemplate, json);
http://jsfiddle.net/mblase75/H8tqn/
Actually you can do it with only Mustache, but for the case your JSON contains not only a number, but an array of values, together with the size of the array:
var json = {
'rows': ['a','b','c'],
'numRows': function() {
return this.rows.length
}
} // ajax response data json.
In order to do it, you can use one of the following Mustache templates:
In the simple case, when you just need to add "s" for plural:
var myTemplate = '{{ numRows }} link{{^rows}}s{{/rows}}{{#rows.1}}s{{/rows.1}} parsed so far.'
The result:
0 links parsed so far.
1 link parsed so far.
2 links parsed so far.
In the general case, when the plural is special (like people/person):
var myTemplate2 = '{{ numRows }} {{^rows}}people{{/rows}}{{#rows.0}}{{^rows.1}}person{{/rows.1}}{{/rows.0}}{{#rows.1}}people{{/rows.1}} joined so far.'
The result:
0 people joined so far.
1 person joined so far.
2 people joined so far.
You can find both templates applied in practice here: http://jsfiddle.net/H8tqn/9/
P.S. I will post again here if I can find the solution for this one:
No people joined so far.
1 person joined so far.
2 people joined so far.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With