本文介绍了使用 TranslationServiceProvider 处理 Silex 上的 {_locale} 前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使我正在开发的网站可翻译.由于我使用 Silex,因此我选择了运行良好的 TranslationServiceProvider.

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.

这是我来自 app.php 的代码:

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

这是我的路由器 (routes.php) 的开头:

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

问题是我不知道如何用 {_locale} 为我的所有路由添加前缀.如果我这样做,不带前缀的 URL 会导致 404 错误.

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.

我看到了 Symfony 的这个解决方案:

I saw this solution for Symfony :

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

但它需要一个 .yml 路由器,我不知道它是否与 Silex 的工作方式相同(我以前从未使用过 .yml 文件,所以我有点迷茫).

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) ?

推荐答案

你可以在路由中添加 _locale 参数

You can add _locale parameter in your routes

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

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

这篇关于使用 TranslationServiceProvider 处理 Silex 上的 {_locale} 前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 04:36