dsaj20411 2015-12-05 18:54
浏览 27
已采纳

使用TranslationServiceProvider处理Silex上的{_locale}前缀

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条回答 默认 最新

  • dongshi6710 2015-12-06 13:25
    关注

    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');

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助