w3lifer/yii2-i18n-js

Yii2 国际化 JavaScript 实现

1.0.1 2024-09-15 16:34 UTC

This package is auto-updated.

Last update: 2024-09-26 17:55:21 UTC


README

安装

composer require w3lifer/yii2-i18n-js

使用方法

1. 在 @app/config/web.php 中配置以下组件

<?php

return [
    // ...
    'components' => [
        'i18n' => [ // https://yiiframework.cn/doc/guide/2.0/en/tutorial-i18n
            'translations' => [
                '*' => [
                    'class' => \yii\i18n\PhpMessageSource::class,
                ],
            ],
        ],
        'i18nJs' => [
            'class' => \w3lifer\Yii2\I18nJs::class,
        ],
        // ...
    ],
    // ...
];

2. 创建 @app/messages/ru/app.php 并包含以下内容

<?php

return [
    'Hello, World!' => 'Привет, Мир!',
    'Hello, {username}!' => 'Привет, {username}!',
    'Hello, {0} {1}!' => 'Привет, {0} {1}!',
];

3. 创建 @app/controllers/I18nJsController

<?php

namespace app\controllers;

class I18nJsController extends \yii\web\Controller
{
    public function actionIndex(): string
    {
        return $this->render('index');
    }
}

4. 创建 @app/views/i-18-js/index.php ...

请注意,在使用前需要初始化 i18n 组件。
您可以在任何位置进行初始化,例如在 @app/views/layouts/main.php 中,只需触摸它即可。

Yii::$app->i18nJs;

但是,不要在将由 AJAX 请求处理的地方修改组件
(例如,在 @app/config/web.php -> bootstrapon afterRequest 等),
因为这会导致组件被加载两次,这是没有意义的。

<?php

/**
 * @see \app\controllers\I18nJsController::actionIndex()
 *
 * @var \yii\web\View $this
 *
 * @see https://:809/i-18n-js
 */

Yii::$app->i18nJs;

Yii::$app->language = 'ru';

$this->title = 'I18nJs';

?>

<script>
    // Use case #1
    window.addEventListener('DOMContentLoaded', _ => {
      console.log('------------------- Use case #1')
      console.log(yii.t('app', 'Hello, World!')) // Привет, Мир!
      console.log(yii.t('app', 'Hello, {username}!', {username: 'John'})) // Привет, John!
      console.log(yii.t('app', 'Hello, {0} {1}!', ['John', 'Doe'])) // Привет, John Doe!
      console.log(yii.t('app', 'Hello, {0} {1}!', ['John', 'Doe'], 'en')) // Hello, John Doe!
    })
</script>

<?php

// Use case #2 (the contents of the [i18nTest.js] file are the same as in use case #1)

$this->registerJsFile('/js/i18nTest.js');

// Use case #3

$this->registerJs(<<<JS
    console.log('------------------- Use case #3')
    console.log(yii.t('app', 'Hello, World!')) // Привет, Мир!
    console.log(yii.t('app', 'Hello, {username}!', {username: 'John'})) // Привет, John!
    console.log(yii.t('app', 'Hello, {0} {1}!', ['John', 'Doe'])) // Привет, John Doe!
    console.log(yii.t('app', 'Hello, {0} {1}!', ['John', 'Doe'], 'en')) // Hello, John Doe!
JS);

5. 将 I18nJs::$jsFilename(默认:@app/web/js/i18n.js)添加到 @app/.gitignore

# w3lifer/yii2-i18n-js
/web/js/i18n.js

6. 访问 http://example.com/i-18n-js 并在浏览器控制台中查看结果。