Commit de9df3de authored by Fabien Potencier's avatar Fabien Potencier

added TranslationExtension

Usage:

$app = new Application();
$app->register(new TranslationExtension(), array(
    'translation.class_path' => '...',
));

$app['translator.messages'] = array(
    'en' => array(
        'apple' => 'apple',
    ),
    'fr' => array(
        'apple' => 'pomme',
    ),
);

$app['locale'] = 'fr';

echo $app['translator']->trans('apple');

If you use the Symfony Bridge extension, some tags and filters are also
automatically available in templates:

$templates = array(
    'index' => '{% trans %}apple{% endtrans %}'
);
parent b550703b
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex\Extension;
use Silex\Application;
use Silex\ExtensionInterface;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\ArrayLoader;
class TranslationExtension implements ExtensionInterface
{
public function register(Application $app)
{
$app['translator'] = $app->share(function() use ($app) {
$translator = new Translator(isset($app['locale']) ? $app['locale'] : 'en', $app['translator.message_selector']);
if (isset($app['locale_fallback'])) {
$translator->setFallbackLocale($app['locale_fallback']);
}
$translator->addLoader('array', $app['translator.loader']);
foreach ($app['translator.messages'] as $locale => $messages) {
$translator->addResource('array', $messages, $locale);
}
return $translator;
});
$app['translator.loader'] = $app->share(function() use ($app) {
return new ArrayLoader();
});
$app['translator.message_selector'] = $app->share(function() use ($app) {
return new MessageSelector();
});
if (isset($app['translation.class_path'])) {
$app['autoloader']->registerNamespace('Symfony\\Component\\Translation', $app['translation.class_path']);
}
}
}
......@@ -14,6 +14,7 @@ namespace Silex\Extension;
use Silex\Application;
use Silex\ExtensionInterface;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Bridge\Twig\Extension\TransExtension;
class TwigExtension implements ExtensionInterface
{
......@@ -26,8 +27,14 @@ class TwigExtension implements ExtensionInterface
$app['twig.configure']($twig);
}
if (isset($app['url_generator']) && isset($app['symfony_bridges'])) {
$twig->addExtension(new RoutingExtension($app['url_generator']));
if (isset($app['symfony_bridges'])) {
if (isset($app['url_generator'])) {
$twig->addExtension(new RoutingExtension($app['url_generator']));
}
if (isset($app['translator'])) {
$twig->addExtension(new TransExtension($app['translator']));
}
}
return $twig;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment