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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?