如何在slim框架中替换翻译器实例?

时间:2017-12-08 10:52:27

标签: php laravel twig translation slim

我正在使用苗条和Laravel的照明/翻译。我是所有这一切的新手,我找到了翻译我的页面的解决方案,但是当我试图在运行期间将另一个翻译器实例(将页面的翻译更改为)时,我遇到了问题是时候改变翻译了。 这是我正在做的事情: 我有一个像Twig这样的导航栏:

<li><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">lang<span class="caret"></span> </a>
                    <ul class="dropdown-menu">
                        <li><a href="{{path_for('en')}}" >english</a> </li>
                        <li><a href="{{path_for('fr')}}">french</a> </li>
                    </ul>
                    </li>

和语言控制器,我将转换器的新实例设置为容器:

  public function getFrench($request, $response){
    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );
     // Register the french translator (set to "en" for English)
    $translator = new Translator($loader, "fr");

    $this->translator=$translator;

   }

这就是我的容器设置方式:

$container['translator']= function($container){

    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );
     // Register the french translator (set to "en" for English)
    $translator = new Translator($loader, "en");

    return $translator;
};

**我正在添加translationExtension的视图**:

$container['view']= function($container){
    $view= new \Slim\Views\Twig(__DIR__ .'/../resources/views',['cache'=> false,]);

     // add translator functions to Twig
    $view->addExtension(new TranslatorExtension($container->get('translator')));

    return $view;

};

我不知道是否以错误的方式进行此操作,因为无论我做什么我都无法在运行时更改翻译,我总是得到我在容器内设置的翻译(在本例中为英文),我应该使用全局变量而不是控制器方式?我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

你可以use the Accept-Language-header to detect which language a user want to see。这可以在中间件中进行。

首先,您应该从容器中删除扩展名添加

$container['view']= function($container){
    $view= new \Slim\Views\Twig(__DIR__ .'/../resources/views',['cache'=> false,]);
    return $view;
};

然后通过中间件添加扩展,解析后的语言形成标题:

$container = $app->getContainer();
$app->add(function (\Slim\Http\Request $request, $response, $next) use ($container) {
    $lang = $request->getHeader('Accept-Language');

    // $lang could be something like 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'
    // see above link for more information about parsing it
    $parsedLang = parseLang($lang);

    $loader = new FileLoader(new Filesystem(),  __DIR__ . '/../resources/lang' );

    $translator = new Translator($loader, $parsedLang);

    // add the extension to twig
    $view = $container->get('view');
    $view->addExtension(new TranslatorExtension($translator));

    // execute the other middleware and the actual route
    return $next($request, $response);
});