Lately I had to do more work with ExtJS x-templates, and really found them very flexible. One feature I find useful is the support for formatting functions. So you can have a template which outputs different things for plural and singular forms:

new Ext.XTemplate('{0:plural("record","records")} deleted').apply([4]) 
// -> 4 records deleted

This is nice. Yet the formatting functions are not limited to just a few. Templates support all formatting functions in Ext.util.Format. What’s even better is that you can add your own formatting functions and have them in the templates.

One use case for this usage of templates is displaying user feedback in a label or tooltip when deleting records in a grid, or selecting records. In order to be accurate and give a nice user experience, it would be nice to output: ‘No records selected’, and not ’0 records selected’; ‘One record selected’, and not ’1 record selected’. So, a nice solution would be the following:

(function() {


         * Label plural formatter : lplural - to be used with templates
         * @param value {Number} number
         * @param singular {String} singular form
         * @param plural {String} plural form
         * @param zero {String} zero form
         * @param addPluralValue {Boolean} whether to add 
         *            the value in the plural form
        lplural: function(value, singular, plural, zero, addPluralValue){
            //make the text for the zero quantity be optional
            if (zero && !value){
                return zero;

            //also the addPluralValue flag is optional - if it is true, 
           //also return the value: eg - 5 records 
            plural = addPluralValue? (value + ' ' + plural) : plural;

            return value != 1 ? plural : singular;


        var t = new Ext.XTemplate('{0:lplural("one record","records","no records", true)}');

        //add plural value
        console.log(t.apply([5])) // -> 5 records

        console.log(t.apply([0])) // -> no records
        console.log(t.apply([1])) // -> one record

        var t = new Ext.XTemplate('{0:lplural("one record","records", null , false)}');

        //don't output the '5'
        console.log(t.apply([5])) // -> records
       //haven't provided a text for zero, so defaults to the plural form
        console.log(t.apply([0])) // -> records

I really think templates are very powerful, so use them! Any other clever usages? (besides all the ext4 being built on top of them :) )

Leave a reply


<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>