Created
April 19, 2017 07:10
-
-
Save geertw/670536de46b401de960282071dfbc1d2 to your computer and use it in GitHub Desktop.
Language switcher example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace frontend\components; | |
use Yii; | |
use yii\bootstrap\Dropdown; | |
class LanguageSwitcher extends Dropdown { | |
private static $_labels; | |
private $_isError; | |
public function init() { | |
$route = Yii::$app->controller->route; | |
$params = $_GET; | |
$this->_isError = $route === Yii::$app->errorHandler->errorAction; | |
array_unshift($params, '/' . $route); | |
foreach (Yii::$app->urlManager->languages as $language) { | |
$isWildcard = substr($language, -2) === '-*'; | |
if ($isWildcard) { | |
$language = substr($language, 0, 2); | |
} | |
$params['language'] = $language; | |
$params['url-language'] = $language; | |
$this->items[] = [ | |
'label' => self::label($language), | |
'url' => $params, | |
]; | |
} | |
parent::init(); | |
} | |
public function run() { | |
// Only show this widget if we're not on the error page | |
if ($this->_isError) { | |
return ''; | |
} else { | |
return parent::run(); | |
} | |
} | |
public static function label($code) { | |
if (self::$_labels === null) { | |
self::$_labels = [ | |
'nl' => 'Nederlands', | |
'en' => 'English', | |
]; | |
} | |
return isset(self::$_labels[$code]) ? self::$_labels[$code] : null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment