ZF2 Tips: Localizing Plurals

Just want to jot this down so I don't forget (and maybe it can help someone else). I spent an inordinate amount of time wrestling with the ZF2 documentation trying to find out how to do pluralized translations, so hopefully you won't have to.

Here is the proper structure for a plural localization in a gettext ".po" file:

msgid "Found %d Result"
msgid_plural "Found %d Results"
msgstr[0] "Found %d Result"
msgstr[1] "Found %d Results"

Some languages might have 1 or 3 (or more) plural forms. If you look in the header of the .po file, there is a line that starts like this that tells you how many plural forms you should localize to:

"Plural-Forms: nplurals=2; plural=(n != 1);\n"

So you can see that "nplurals" is 2 for English. If it were some other language (such as Polish), it might be 3, in which case the localization would look like this:

msgid "Found %d Result"
msgid_plural "Found %d Results"
msgstr[0] "singular localization here"
msgstr[1] "plural localization here"
msgstr[2] "super plural localization here"

This seems to be the proper way to get Zend Framework 2's ->translatePlural() method to work properly. In a view helper, you would invoke it like so:

<h2><?php echo sprintf($this->tp(‘Found %d Result', ‘Found %d Results', $number), $number); ?></h2>

I hope this helps someone out.


Building a gettext ".mo" file from a ".po" file:

$ msgfmt default.po -o default.mo

Published: March 9, 2015

Categories: howto

Tags: zf2, zend framework 2, dev, development, coding, internationalization, localization, i18n, l10n, howto

Related Posts
comments powered by Disqus