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 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题