简体   繁体   中英

choose language in the zend framework 2 website

I use the Zend/Translator to translate the text in my website. I set a default local and it works. Now the user should be able to choose the language in the layout.html:

...

<li class="dropdown">
   <a href="<?php echo $this->url('home');?>" class="dropdown-toggle" data-toggle="dropdown">Sprache<b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Deutsch</a></li>
          <li><a href="<?php echo $this->url('application/default', array('action'=>'en'));?>">Englisch</a></li>
          <li><a href="#">Französisch</a></li>
          <li><a href="#">Spanisch</a></li>
        </ul>
</li>

...

The default language is German. Now I try to change the language to English by choosing 'Englisch' in the dropdown-menu. But I don't know what to write in the controller. I tried it like this, but it doesn't work:

public function enAction()
{
    $translator = $this->getServiceLocator()->get('translator');
    $translator->setLocale('en');

    return $this->redirect()->toRoute('home');

}

Can someone help me?

Thanks.

You can have a look at SlmLocale , a module that performs locale detection and storage (either via a session or cookie). With SlmLocale, you can render a menu to switch from locale, all urls are updated accordingly.

echo $this->localeMenu();

SlmLocale is capable of selecting a locale based on the hostname, part of the path (ie /en/my/url ) or query parameter.

Disclaimer: I am the author of SlmLocale :)

the translator doesn't memorize the selected language when you set the locale. you need to keep the selected lang in session for future request. and in you modules bootstrap get the lang from session and set translators locale.

when you want change language should have code to refresh page with append lang parameter to url . Setting is

class Settings{

   const DEFAULT_LANGUAGE = 'en';
   public static $locations = array(
    'sa'=>'sa_SA',
        'en'=>'en_US'
    );
}

and in Application\\Module.php

public function onBootstrap(MvcEvent $e) {
    $lang = $e->getRequest()->getQuery('lang'); // new language
    $session = new Container('base');
    if($lang == null || $lang == ''){
        if ($session->offsetExists('lang')) {
            $lang = $session->offsetGet('lang'); // current language
        }else{
            $lang = 'en; // default language
        }
    }
    $session->offsetSet('lang', $lang);
    $loc = Settings::$locations[$lang];
    $translator
    ->setLocale($loc)
    ->setFallbackLocale(Settings::DEFAULT_LANGUAGE .'_' . Settings::DEFAULT_LOCATION);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM