handle {_locale} prefixes on Silex with the TranslationServiceProvider

女生的网名这么多〃 提交于 2019-12-11 12:26:29

问题


I am trying to make the website I am working on, translatable. As I am using Silex, I chose the TranslationServiceProvider which is working nicely.

Here is my code from app.php :

$app->register(new Silex\Provider\TranslationServiceProvider(), array(
    'locale' => 'en',
    'locale_fallback' => array('en'),
));
$app['translator'] = $app->share($app->extend('translator', function($translator, $app) {
    $translator->addLoader('yaml', new YamlFileLoader());
    $translator->addResource('yaml', __DIR__.'/locales/en.yml', 'en');
    $translator->addResource('yaml', __DIR__.'/locales/fr.yml', 'fr');

    return $translator;
}));

And here is the beginning of my router (routes.php) :

// Home page
$app->get('/', "FarmaDubno\Controller\HomeController::indexAction")->bind('home');

// View an existing news
$app->get('/news/{id}', "FarmaDubno\Controller\HomeController::newsAction")->bind('newsAction');

// Activities page
$app->get('/activities', "FarmaDubno\Controller\HomeController::activitiesAction")->bind('activities');

// View an existing activity
$app->get('/activity/{id}', "FarmaDubno\Controller\HomeController::activityAction")->bind('activityAction');

The problem is that I don't know how to prefix all my routes with {_locale}. If I do it, the unprefixed URL leads to a 404 error.

I saw this solution for Symfony :

oc_platform:
    resource: "@OCPlatformBundle/Resources/config/routing.yml"
    prefix:   /{_locale}/platform
    requirements:
        _locale: en|fr

But it requires a .yml router and I don't know if it works the same way with Silex (I've never used .yml files before now so I am kind of lost).

How can I prefix my routes without having to rewrite everything (which would be very ugly) ?


回答1:


You can add _locale parameter in your routes

$app->get('/{_locale}/', "FarmaDubno\Controller\HomeController::indexAction")->bind('home')->assert('_locale', 'en|fr');

or

$app->get('/{_locale}/news/{id}', "FarmaDubno\Controller\HomeController::newsAction")->bind('newsAction')->assert('_locale', 'en|fr');



来源:https://stackoverflow.com/questions/34109527/handle-locale-prefixes-on-silex-with-the-translationserviceprovider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!