sergmoro1 / yii2-lang-switcher
Language switcher for a site content.
Installs: 63
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 0
Type:yii2-extension
pkg:composer/sergmoro1/yii2-lang-switcher
Requires
- yiisoft/yii2: *
This package is auto-updated.
Last update: 2025-10-12 06:42:50 UTC
README
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> <p class='en'> Text in native language. </p>
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.
Installation
In app directory:
$ composer require sergmoro1/yii2-lang-switcher "dev-master"
Usage
Register widget in app -common/config/main.php:
<?php
return [
...
'bootstrap' => [
'LangSwitcher',
],
...
'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; ... <body> <?= 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 theexcludeByLanguage().
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.