dev-master
9999999-devLanguage switcher for a site content.
MIT
The Requires
by Sergey Morozov
language yii2 multi
Language switcher for a site content.
Yii has multi-language support, but there are not about content. Content, ordinary, should be on a different sites., (*1)
But, for blog, it's not convenient. Simpler translate right in place:, (*2)
<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., (*3)
Fields with a "short" length (e.g. "title"), language version divided by "/"., (*4)
This approach is implemented in this little extension for two languages., (*5)
Languages can be arbitrary., (*6)
In app directory:, (*7)
$ composer require sergmoro1/yii2-lang-switcher "dev-master"
Register widget in app - common/config/main.php
:, (*8)
<?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., (*9)
... use sergmoro1\langswitcher\widgets\LangSwitcher; ... <body> <?= LangSwitcher::widget(); ?>
In menu place the switcher:, (*10)
<?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
., (*11)
public function behaviors() { return [ 'LangSwitcher' => ['class' => LangSwitcher::className()], ]; }
Post content can be shown in frontend/views/post/view.php
, (*12)
<?= $model->excludeByLanguage('content'); ?>
and title., (*13)
<?= $model->splitByLanguage('title'); ?>
Data to be displayed uniformly, including RSS, need in the model common/models/Post.php
to define a method fields
, (*14)
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', ]; }
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., (*15)
use sergmoro1\langswitcher\controllers\Controller; class SiteController extends Controller {
Remember that in the sitemap
is also necessary to take into account the language version., (*16)
Language switcher for a site content.
MIT
language yii2 multi