M
M
MSAFT2019-06-10 17:14:24
Laravel
MSAFT, 2019-06-10 17:14:24

How to translate a string in VueJS from Laravel?

Good day. There was such a problem, I use VueJS to translate strings through Laravel through the following API:

Route::get('/js/lang-js', function () {
        Cache::forget('lang-js');
        $strings = Cache::rememberForever('lang-js', function () {
        $lang = config('app.locale');

        $files   = glob(resource_path('lang/' . $lang . '/*.php'));
        $strings = [];

        foreach ($files as $file) {
            $name           = basename($file, '.php');
            $strings[$name] = require $file;
        }

        return $strings;
    });

    header('Content-Type: text/javascript');
    echo('window.i18n = ' . json_encode($strings) . ';');
    exit();
})->name('assets.lang');

It works great in the template through: But the lines in the code itself cannot be translated in this way, what to do? Don't write like this:
{{ trans('translation_file.translation_caller') }}
if(document.getElementsByTagName("html")[0].getAttribute("lang") === 'ru') {
                    swal({
                        position: 'top-end',
                        type: 'success',
                        title: 'Добавлено в корзину', //строка которую надо перевести
                        showConfirmButton: false,
                        timer: 1500
                    })
                }
                else if(document.getElementsByTagName('html')[0].getAttribute("lang") === 'en') {
                    swal({
                        position: 'top-end',
                        type: 'success',
                        title: 'Added to cart',
                        showConfirmButton: false,
                        timer: 1500
                    })
                }

I would like something a little more elegant. Should I use components? Has anyone had a similar experience?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2019-06-11
@MSAFT

There is already such a bike: vue-i18n , and there is a package for Laravel to link with vue-i18n.

J
John Bjornsen, 2020-11-22
@Bjornsen

You can try this approach - https://github.com/keeborg/laravel-js-simple-trans...
All translations are generated into a single .json file and then used by a custom class. As a result, you can use translations from the stall with the same keys, for example $t.__('translation_file.translation_caller'); The language used is automatically determined inside the class, the main thing is not to forget to hang the lang="" attribute on the html tag, but it seems to be in the lark out of the box

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question