ZF3路由语言环境参数

时间:2019-02-23 10:14:04

标签: zend-framework3

我在项目中翻译了模板和路线。设置语言环境后,翻译正常,但链接中的语言环境参数不正确。 我的默认语言是NL。所以我有一个页面www.website.com/nl/contact 当我切换到语言fr时,我转到www.website.com/fr/contact,然后在HTML源代码中查找时,链接仍然是www.website.com/nl/contact而不是www.website.com/fr/contact,因此区域设置链接中的参数不会针对setLocale进行更新

我的module.php

public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();

    $eventManager->attach(
        \Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR,
        function ($e) {
            $application    = $e->getApplication();
            $match          = $application->getMvcEvent()->getRouteMatch();

            if (null === $match) {
                $params     = [
                    '__NAMESPACE__' => 'Application\Controller',
                    'controller'    => 'Index',
                    'action'        => 'not-found',
                    // Here you can add common params for your application routes
                ];

                $viewModel = $e->getViewModel();
                $viewModel->setTemplate('layout/website');

                $routeMatch = new RouteMatch($params);

                $routeMatch->setMatchedRouteName('home');
                $application->getMvcEvent()->setRouteMatch(
                    $routeMatch
                );
            }
        }
    );

    $moduleRouteListener = new ModuleRouteListener();

    if (!$e->getRequest() instanceof ConsoleRequest) {

        $this->setLanguage($e);
        $eventManager->attach('route', array($this, 'onPreRoute'), 100);
        $moduleRouteListener->attach($eventManager);

        $this->initAcls($e);

        if (isset($_SERVER['APP_ENV']) and $_SERVER['APP_ENV'] == 'production') {
            $eventManager->attach('finish', array($this, 'outputCompress'), 100);
        }
    }
}

private function setLanguage($e)
{
    $redirectBase   = $e->getRequest()->getServer()->get('REDIRECT_BASE');
    $requestUri = $e->getRequest()->getServer()->get('REQUEST_URI');

    $cmsString      = substr($requestUri, strlen($redirectBase), 4);
    $language = 'nl';
    $routeTranslation = true;

    if ($requestUri != '/') {
        $language = substr($requestUri, 1, 2);
    }

    if ($cmsString == 'cms/') {
        $language = 'en-us';
        $routeTranslation = false;
    }

    $translator = $e->getApplication()->getServiceManager()->get('MvcTranslator');
    $translator->setLocale($language);

    if ($routeTranslation) {
        $translator->addTranslationFile('PhpArray', __DIR__.'/../language/Routes/' . $language . '.php', 'default', $language);
    }
}

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

0 个答案:

没有答案