laovejabohem/yii2-i18n-js-db

Yii2 internationalization in JavaScript using database storage

v1.0.5 2025-04-17 17:01 UTC

This package is not auto-updated.

Last update: 2025-04-18 16:45:46 UTC


README

Installation

composer require w3lifer/yii2-i18n-js

Database Setup

  1. Run the database migration to create the translations table:
yii migrate --migrationPath=@vendor/w3lifer/yii2-i18n-js/src/migrations
  1. Add translations to the database using SQL or through your application:
-- First, insert the source messages
INSERT INTO source_message (id, category, message) VALUES
(1, 'app', 'Hello, World!'),
(2, 'app', 'Hello, {username}!'),
(3, 'app', 'Hello, {0} {1}!');

-- Then, insert the translations
INSERT INTO message (id, language, translation) VALUES
(1, 'ru', 'Привет, Мир!'),
(2, 'ru', 'Привет, {username}!'),
(3, 'ru', 'Привет, {0} {1}!');

Usage

1. Configure the following components in @app/config/web.php:

<?php

return [
    // ...
    'components' => [
        'i18n' => [ // https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n
            'translations' => [
                '*' => [
                    'class' => \yii\i18n\DbMessageSource::class,
                    'sourceMessageTable' => '{{%source_message}}',
                    'messageTable' => '{{%message}}',
                ],
            ],
        ],
        'i18nJs' => [
            'class' => \w3lifer\Yii2\I18nJs::class,
        ],
        // ...
    ],
    // ...
];

2. The translations are now stored in the database instead of PHP files. Use Yii2's message command to extract messages and store them in the database:

yii message/extract @app/config/i18n.php

Create @app/config/i18n.php with the following content:

<?php
return [
    'sourcePath' => '@app',
    'languages' => ['ru'], // list your languages
    'translator' => 'Yii::t',
    'sort' => true,
    'removeUnused' => false,
    'markUnused' => true,
    'only' => ['*.php'],
    'except' => [
        '.svn',
        '.git',
        '.gitignore',
        '.gitkeep',
        '.hgignore',
        '.hgkeep',
        '/messages',
        '/vendor',
    ],
    'format' => 'db',
    'db' => 'db',
    'sourceMessageTable' => '{{%i18n_messages}}',
];

3. Create @app/controllers/I18nJsController:

<?php

namespace app\controllers;

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

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

PLEASE NOTE that the i18n component needs to be initialized before use.
You can do this anywhere, for example in @app/views/layouts/main.php, just touch it.

Yii::$app->i18nJs;

BUT don't touch the component in places that will be handled by AJAX requests
(e.g., in @app/config/web.php -> bootstrap, on afterRequest, etc),
because it will be loaded twice and that doesn't make sense.

<?php

/**
 * @see \app\controllers\I18nJsController::actionIndex()
 *
 * @var \yii\web\View $this
 *
 * @see http://localhost: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. Add I18nJs::$jsFilename (default: @app/web/js/i18n.js) to @app/.gitignore:

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

6. Go to http://example.com/i-18n-js and view the result in your browser console.