Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache JS and singular/plural

Tags:

mustache

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 ?

like image 883
Hellnar Avatar asked Nov 15 '11 14:11

Hellnar


2 Answers

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/

like image 198
Blazemonger Avatar answered Jan 23 '23 05:01

Blazemonger


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.
like image 27
Sorin Postelnicu Avatar answered Jan 23 '23 07:01

Sorin Postelnicu