Conditionally Display the Singular or Plural Form of Words
Page 1 of 4
Written by
Gregory Scot Collins
Tuesday, 30 January 2007, 5:33 AM
This article has been tested to work with the following products and versions. No guarantee of compatibility, with or without modification, is offered for products or versions other than those listed.
IN THIS ARTICLE:
When displaying counts of items, we must decide how to deal with the need to display singular and plural items. There are a number of ways to deal with the issue. One common approach is to simply avoid the issue by not using words that can be represented in both the singular and plural. For example if we are displaying the number of widgets an online store has in stock, we can avoid plurality by just stating the number in stock: "1 in stock", "4 in stock", etc. Another way to avoid the issue is with the common and acceptable approach of using parentheses: "1 widget(s) in stock", "4 widget(s) in stock", etc.
While both of the above approaches have their place, it is not always desirable or acceptable to avoid the issue. Since XSL transforms have the capability to conditionally output content, we can take advantage of this to make our presentation more appealing. We will demonstrate two approaches, both accomplishing the same task with the same results. The first approach will follow the traditional use of XSLT to accomplish the task, while the second will use a more innovative, compact approach.
When there is one widget in stock, we want to output, "There is 1 widget in stock," and when there is zero or more than one widget in stock, we want to output, for example, "There are 4 widgets in stock". So we need to conditionally display "is" or "are" and "widget" or "widgets" based on the in stock count.
Because outputting to an attribute, such as an HTML tooltip, is different than outputting an element, we will write our transform to output to both. As you will see, outputting to an attribute using the compact approach is a much easier exercise; your code is less cluttered, and in my opinion, easier to read.
Create the Widgets.xml file
We need a simple XML file to transform that contains a list of widgets for sale and how many are in stock so that we can demonstrate displaying plurality conditionally. Copy the contents of Listing 1 into a text editor, and then save the file as Widgets.xml.
Stumble It!
Digg It!
del.icio.us




