How to print string translation from object created by MO loader
Hi, I have been able to load translation.mo with MO loader. Now, how to print translation of string from object created by MO loader, something like:
echo $translations->gettext('Hello world!', 'optional-textdomain');
With my current knowledge I was not able to figure out from documentation. Is it possible?
You need install the gettext/translator package to use a translator in your templates. Once it's installed:
use Gettext\Translator;
$translator = Translator::createFromTranslations($yourMoTranslations);
echo $translator->gettext('Hello world');
echo $translator->dgettext('textdomain', 'Hello world');
So complete code after
composer require gettext/translator
composer require gettext/gettext
will looks like:
use Gettext\Loader\MoLoader;
use Gettext\Translator;
$loader = new MoLoader();
$translator = Translator::createFromTranslations( $loader->loadFile('languages/file.mo'));
echo $translator->gettext('Hello world');
echo $translator->dgettext('textdomain', 'Hello world');
Right? Do you think you can add this to the main readme file?
Can use __(); function in gettext v5?
Im trying to update version 4.6 to 5.5.1, in 4.6 i was using translations with the gettext extension
@lavitzz The translator functionality is in a different package: https://github.com/php-gettext/Translator
see my previous comments: https://github.com/php-gettext/Gettext/issues/240#issuecomment-559478396
Ok thx, i try:
$translator = Translator::createFromTranslations( $loader->loadFile('languages/file.mo')); TranslatorFunctions::register($translator);
and __() working perfect :)
@lavitzz can you share complete-example code?
@jasomdotnet yes, i use this:
public function __construct(
MoLoader $moLoader,
ContainerInterface $container
) {
$this->moLoader = $moLoader;
$this->langPath = $container->get('LANG_PATH');
$this->languageRealURL = $container->get('LANGUAGE_REAL_URL');
}
public function __invoke()
{
if (! empty($this->languageRealURL)) {
$langFilePath = $this->langPath . $this->languageRealURL . '.mo';
if (file_exists($langFilePath)) {
$translator = Translator::createFromTranslations($this->moLoader->loadFile($langFilePath));
TranslatorFunctions::register($translator);
} else {
throw new FileNotFoundException('File not found: ' . $langFilePath);
}
}
}
I'm sharing my code so far:
use Gettext\Translator;
use Gettext\Loader\MoLoader;
$lang = 'sk' // set by a side function
define('ROOT', '/path/to/root');
function __( string $string, string $textdomain = null ) {
static $t = null;
global $basic_lang;
$translation = ROOT . '/languages/' . $lang . '.mo';
if (!file_exists( $translation )) {
return $string;
}
if ($t === null) {
$loader = new MoLoader();
$t = Translator::createFromTranslations( $loader->loadFile( $translation ) );
}
//return $textdomain ? $t->dgettext( $textdomain, $string ) : $t->gettext( $string );
return $t->gettext( $string );
}
//echo __( 'Buy a ticket', 'reservation' );
echo __( 'Buy a ticket' );