PHP code example of ranvis / leantrans

1. Go to this page and download the library: Download ranvis/leantrans library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ranvis / leantrans example snippets


use Ranvis\LeanTrans;

r(): LeanTrans\Translator
{
    $msgs = [
        '' => [ // the default domain
            'ID_GREETING' => 'Ciao, {name}!',
        ],
    ];
    $provider = new LeanTrans\ArrayProvider($msgs);
    $formatter = new LeanTrans\MessageFormatter('it'); // target locale
    return new LeanTrans\Translator($provider, $formatter);
}

// define helper function
function __(string $msg, ?array $params = null): string
{
    static $translator;
    $translator ??= getTranslator();
    return $translator->translate($msg, $params);
}

// call it
echo __('ID_GREETING', ['name' => 'PHP']);

use Ranvis\LeanTrans;

r = new \Twig\Loader\ArrayLoader([
    'test' => <<<'END'
        <p>{{ "Hello, %name%!"|trans({name}) }}</p>
        <p>{{ "Hello, %name%!"|t({name}) }}</p>
        <p>{% trans with {name: name|e} %}Hello, %name%!{% endtrans %}</p>
        END,
]);
$twig = new \Twig\Environment($loader);

// set up a translator
$msgs = [
    '' => [ // the default domain
        'Hello, %name%!' => 'Ciao, %name%!',
    ],
];
$provider = new LeanTrans\ArrayProvider($msgs);
$formatter = new LeanTrans\VarFormatter();
$twig->addExtension(new LeanTrans\TwigTranslator($provider, $formatter));

// render
echo $twig->render('test', ['name' => 'PHP']);