Rob's Tips and TricksSaturday, July 10, 2010I have been working on a back-end management UI for a client of mine, and ran into an old, old problem in web development - plural nouns. I found my code filled with lots of conditional code to determine when to add an "s" to things, eg: "You have 1 active listing" vs "You have 2 active listings"
In Rails, I have a pluralize method to help (though it only goes so far), and I was looking for something similar in PHP, which led me to this excellent post over at kuwamoto.org. It was the perfect thing - a port of Rails' pluralize/singularize methods in PHP, with a few improvements to boot. Once I had the code installed on our system, however, I found that it wasn't enough. I still had conditionals. I still had blocks of ugly code to make things work. So I came up with something better... The Clever BitI wrote the following function to take not a single word, but a phrase. It pulls out the last word in the phrase, and pluralizes it. The clever bit is, if there's a number in the phrase, it conditionally pluralizes the last word. This was exactly what I needed in my code, and allows me to concisely and elegantly solve one of those niggling problems all web developers deal with. Check out the function here:
ExamplesHere are some sample strings, and the result of running them through smart_pluralize():
Integrating it with SmartyNow that I had a smart phrase pluralizer, I needed to integrate it into Smarty, my template system of, er, choice. :-) I wrote a Smarty block helper named "pluralize" that simply passed the contained text into smart_pluralize() and voila! Clean templates:
Just write your text in singular, include the count in the phrase somewhere, and you're off and running. It's been a real blessing, hope you find it helpful as well!
Posted
by Rob
at 11:11 PM
Add a comment
|
AboutWeb home of Rob Morris, software guru and all-around great guy. A place to post and discuss code and the software development lifestyle. ArchiveJuly 2010 (1)September 2009 (1)August 2009 (2) |