user1130272
user1130272

Reputation:

Laravel string localization and AngularJS

So recently i started to convert my jQuery stuff to AngularJS, but there was a solution what i did not think about.

Not all my pages will use Angular, and i am using Laravel's built in localization.

So the views used by Angular are just plain html, no php or blade included.

So i do not really want to mix the 2 in a view.

Where i use blade i use the built in function example: {{ trans('user.first_name') }}

But since i don't want to mix, and my AngularJS views are pure html, i do not want to use it this way <?php echo trans('user.first_name') ?> in my Angular view.

So i was thinking to include Angular localization for AngularJS, but maintaining 2 different localization structure will be a pain and building a good logic for it is another pain.

So anybody with a solution? currently i am clueless. Because for example with jQuery i did not had to worry about this, because it was just dom manipulation, but now its is more complex

Upvotes: 2

Views: 3844

Answers (2)

everyman
everyman

Reputation: 3407

Solved this with a ViewComposer:

app/Http/ViewComposers/TranslateComposer.php

<?php
namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;

class TranslateComposer
{
    /**
     * Bind data to the view.
     *
     * @param  View $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('jstrans', json_encode(trans('my_locale_resource')));
    }
}

app/Providers/AppServiceProvider.php

public function boot()
{
    view()->composer(
        '*', 'App\Http\ViewComposers\TranslateComposer'
    );
}

resources/views/index.blade.php

<script type="text/javascript">
    var trans = JSON.parse('{!! $jstrans !!}');
</script>

Upvotes: 0

Rubens Mariuzzo
Rubens Mariuzzo

Reputation: 29241

I have developed a package that create a JavaScript file from all Laravel's messages. I think you could use it to have access directly in Laravel.

Basically, after installing the package and running the bundled command you will have a global object: windows.Lang. From there you can do different basic operations such as:

Get a localized message

var message = Lang.get('messages.first_name');

Get a localized message with replacements

var message = Lang.get('messages.welcome', { name: 'Joe' });

Change the current locale (applies to JavaScript)

Lang.setLocale('es');

You can find more information: https://github.com/rmariuzzo/laravel-js-localization

Upvotes: 3

Related Questions