3

我想知道是否可以在 zf2 中为路由/uris 使用翻译工具。例如,我想要将路径en.domain.tld/article/show/1转换为de.domain.tld/artikel/anzeigen/1​​. 我不认为正则表达式是去这里的方式,因为它可能会导致类似en.domain.tld/artikel/show/1. 另外我想避免为每种语言创建路由,因为随着系统的扩展它会变得非常混乱。

4

3 回答 3

6

I was able to get it working!

First, add a 'router_class' => 'Zend\Mvc\Router\Http\TranslatorAwareTreeRouteStack', your module.config.php like this:

return array (
    'router' => array (
        'router_class' => 'Zend\Mvc\Router\Http\TranslatorAwareTreeRouteStack',
        'routes' => array(),
    )
);

Second, you must provide a translator (preferably in your module.php) as well as a translation file:

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        // Load translator
       $translator = $e->getApplication()->getServiceManager()->get('translator');
       $translator->setLocale('de_DE');        

           // setup the translation file. you can use .mo files or whatever, check the translator api
           $translator->addTranslationFile('PhpArray', __DIR__.'/language/routes/de_DE.php', 'default', 'de_DE');

       $app      = $e->getTarget();

       // Route translator
       $app->getEventManager()->attach('route', array($this, 'onPreRoute'), 100);
    }

    public function onPreRoute($e){
        $app      = $e->getTarget();
        $serviceManager       = $app->getServiceManager();
        $serviceManager->get('router')->setTranslator($serviceManager->get('translator'));
    }
}

now, you should be able to use translations in your route definitions like the following:

return array (
    'router' => array (
        'routes' => array(
            'login' => array (
            'type' => 'Zend\Mvc\Router\Http\Segment',
            'may_terminate' => true,
            'options' => array (
                'route' => '/{login}',
                'defaults' => Array(
                    'controller' => '...',
                ) 
            ),
        ),
    )
);

create the translation (in this example a phpArray located in module/language/routes/de_DE.php):

<?php
return array(
    'login' => 'anmelden',
);

If I didn't forget anything, you should be good to go. I got it working in my case, so if it doesn't with the instructions above, don't hesitate to comment and I'll sort things out.

于 2013-07-01T21:57:05.267 回答
1

从 ZF 2.2.0 开始,您会发现已经有一个实现。据我所知,没有此功能的文档,但是在查看单元测试时,您应该可以试一试:

我将尝试在今天某个时候设置一个有效的示例设置,但不能做出任何承诺 - 测试应该让你开始!

于 2013-07-01T06:05:36.923 回答
1

作为上述 onPreRoute 回调的补充:

您可能需要添加:

$serviceManager->get('router')->setTranslatorTextDomain(' TEXT_DOMAIN_HERE ');

于 2013-11-26T17:43:48.533 回答