Created
December 14, 2013 09:12
-
-
Save pherrymason/7957177 to your computer and use it in GitHub Desktop.
PHP gettext and contexts (from: http://www.php.net/manual/en/book.gettext.php#89975)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
And what about pgettext and npgettext? They are there in the gettext documentation, but there aren't in PHP. They're very useful if you have the same messages for translation, but in different contexts, so they should be translated separately and probably differently. | |
Fortunately, there is a simple work-around, which may help: | |
From the gettext.h header one can find out that pgettext() is only a macro calling dcgettext() internally with properly mangled parameters - msgctxt and msgid are glued together with use of ASCII char 4 [EOT, End Of Text]. The same way they're written in .mo files, so it's possible to refer them this way. | |
Here's my "emulated" pgettext() function: | |
<?php | |
if (!function_exists('pgettext')) { | |
function pgettext($context, $msgid) | |
{ | |
$contextString = "{$context}\004{$msgid}"; | |
$translation = dcgettext('messages', contextString,LC_MESSAGES); | |
if ($translation == $contextString) return $msgid; | |
else return $translation; | |
} | |
} | |
?> | |
By default, xgettext doesn't support pgettext function for PHP source files. But there is a parameter which can work-around it. Here's how I call xgettext: | |
xgettext --force-po --keyword="pgettext:1c,2" -c -o messages.po sourceFile.php | |
In sourceFile.php I use the following test code: | |
pgettext('menu', 'Open'); //Substitute "Otwórz" | |
pgettext('forum', 'Open'); //Substitute "Otwarty", different context | |
Generated .po file fragment: | |
msgctxt "menu" | |
msgid "Open" | |
msgstr "Otwórz" | |
msgctxt "forum" | |
msgctxt "Open" | |
msgstr "Otwarty" | |
I've tested it out and everything works fine :-) If anyone have some further suggestions or fixes, please write ;-) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Missing a $ before contextString : $translation = dcgettext('messages', contextString,LC_MESSAGES);