Skip to content

Instantly share code, notes, and snippets.

@geertw
Created April 19, 2017 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geertw/670536de46b401de960282071dfbc1d2 to your computer and use it in GitHub Desktop.
Save geertw/670536de46b401de960282071dfbc1d2 to your computer and use it in GitHub Desktop.
Language switcher example
<?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