Skip to content
Language switcher for a site content
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

Yii2 language switcher

Yii has multi-language support, but there are not about content. Content, ordinary, should be on a different sites.

But, for blog, it's not convenient. Simpler translate right in place:

<p class='ru'>
  Текст на родном языке.
<p class='en'>
  Text in native language.

So, two classes have defined: .ru, .en. For current languge - ru-RU, will show html-tags with class .ru and tags with class .en cleaned up. If has pressed languge switcher, tags with .ru cleaned up and with .en shows.

Fields with a "short" length (e.g. "title"), language version divided by "/".

This approach is implemented in this little extension for two languages.

Languages can be arbitrary.


In app directory:

$ composer require sergmoro1/yii2-lang-switcher "dev-master"


Register widget in app - common/config/main.php:
return [
  'bootstrap' => [
  'modules' => [
    'langswitcher' => ['class' => 'sergmoro1\langswitcher\Module'],
  'components' => [
    'LangSwitcher' => ['class' => 'sergmoro1\langswitcher\widgets\LangSwitcher'],

Call widget in frontend/views/layouts/main.php or any other layout.

use sergmoro1\langswitcher\widgets\LangSwitcher;
<?= LangSwitcher::widget(); ?>

In menu place the switcher:

<?php echo Html::a('rus|eng', ['langswitcher/language/switch']); ?>

In a model should be provided getting data for current language. Behavior shoul be connected in a model /common/models/Post.php.

public function behaviors()
    return [
        'LangSwitcher' => ['class' => LangSwitcher::className()],

Post content can be shown in frontend/views/post/view.php

<?= $model->excludeByLanguage('content'); ?>

and title.

<?= $model->splitByLanguage('title'); ?>

Data to be displayed uniformly, including RSS, need in the model common/models/Post.php to define a method fields

public function fields()
    return [
        'id', 'author_id', 'slug',
        'title' => function ($model) { return $model->splitByLanguage('title'); },
        'content' => function ($model) { return $model->excludeByLanguage('content'); },
        'tags', 'status', 'created_at', 'updated_at', 

Static content

To apply the proposed approach to static pages, you need to pass the content through the filter of the excludeByLanguage(). This requires that frontend/controllers/SiteController inherits from controller defined in the extension.
use sergmoro1\langswitcher\controllers\Controller;

class SiteController extends Controller {

Remember that in the sitemap is also necessary to take into account the language version.

You can’t perform that action at this time.