July 19, 2004

MTPluralize

An example of a tiny MovableType plugin: On this site, the number of comments displayed at the bottom of an entry on the front page says "0 comments" if there are no comments. If there is one comment, it ought to read "1 comment", but the following template code would display "1 comments":

  <$MTEntryCommentCount$> comments

The following is one way to get the desired result.

Create a file named "Pluralize.pl" in your plugins directory. It should contain:

package MTPlugins::Pluralize;
use MT::Template::Context;
 
MT::Template::Context->add_container_tag(Pluralize => \&Pluralize);
 
sub Pluralize {
  my ($ctx, $args, $cond) = @_;
  my $tokens = $ctx->stash('tokens');
  my $builder = $ctx->stash('builder');
  my $text = $builder->build($ctx, $tokens, $cond);
  return $ctx->error($builder->errstr) unless defined $text;
 
  return ($args->{singular} || '') if ($text == 1);
  return $args->{plural} || 's';
}
 
1;

MTPluralize is a "container" tag that replaces its contents with nothing if it contains the number "1", or "s" otherwise. To get "0 comments" or "1 comment" to display, include the following in a template:

<$MTEntryCommentCount$> comment<MTPluralize><$MTEntryCommentCount$></MTPluralize>

MTPluralize can take arguments to specify the text to appear in the singular and plural cases, named "singular" and "plural," respectively.

<$MTEntryCommentCount$> box<MTPluralize plural="es"><$MTEntryCommentCount$></MTPluralize>

This may not be the best way to do it, but it's one way, and it took less than three minutes to write.

Of course someone has already written this plugin: Plural J does it a slightly different way, and may be preferred for some cases, especially if mt-plugins.org's Plugin Manager works as well as it claims to. But in the time it took me to think to check for an existing implementation, I has already written mine.