akdubya / dustjs

Asynchronous templates for the browser and node.js
http://akdubya.github.com/dustjs/
MIT License
1.44k stars 131 forks source link

Plural/singular #64

Open thany opened 11 years ago

thany commented 11 years ago

How to write in the template a conditional block to display a plural or singular label? Say, my json is something like this: { "title": "...", "responses": 4 }

I want my template to be something like this: {title}, {responses} responses.

But for that, if there's 1 response (in this example) I have to determine in the template if the value {responses} is 0, 1, or many. For multilingual purposes, I need all three labels "no responses", "one response" and "X responses" to be in the template.

But how?

thany commented 11 years ago

Okay, these helpers will do what I need:

$.extend(dust.helpers, {
  zero: function(chunk, context, bodies, args) { return Number(args.what) === 0 ? bodies.block(chunk, context) : chunk; },
   one: function(chunk, context, bodies, args) { return Number(args.what) === 1 ? bodies.block(chunk, context) : chunk; },
  many: function(chunk, context, bodies, args) { return Number(args.what) > 1 ? bodies.block(chunk, context) : chunk; }
});

And then in the template:

{@zero what=responses}<span>no responses</span>{/zero}
{@one what=responses}<span>1 response</span>{/one}
{@many what=responses}<span>{responses} responses</span>{/many}

But this kind of functionality is so basic, that I fully expect this to be in the core... If it isn't, then consider this a request ;)

sethkinast commented 9 years ago

You could use some of the logic helpers in https://github.com/linkedin/dustjs-helpers along with LinkedIn's Dust fork. So using the native functionality you could do

<span>
{@eq key=responses value=1}{responses} response{:else}{responses} responses{/eq}
</span>

However the best way would be to create a helper that calls out to something like FormatJS and uses real MessageFormat syntax, because different languages have different pluralization needs. FormatJS even supports Dust templates :)