Reusing translation in Laravel 5.2

I am wondering if localization translations can be reused in Laravel 5.2. So, something like this or better than the real global available keys for direct use brandinstead of entering a folder or file name (in this example global).

// resources/lang/en/global.php
return [
 'brand' => 'Stackoverflow',
 'my'    => 'My :attribute',
 'my_brand' => trans('global.my', ['attribute' => trans('global.brand')])
];

Hope this is a way to reuse translations with Laravel.

+4
source share
2 answers

You should be able to use View Composer to enter your translations globally into all kinds of applications. The steps you must follow are as follows.

  • Creating a composer of the performance
  • Register Presentation Composer to Service Provider
  • .

, App\Http\ViewComposers ( )

class TranslationsComposer
    {
        protected $translations;

        public function __construct()
        {
            $this->translations = [
                'brand' => trans('global.brand'),
                'my' => trans('global.my'),
            ];
        }

        public function compose(View $view)
        {
             $view->with('translations', $this->translations);
        }
    }

, , .

-

namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;
use Illuminate\Users\Repository as UserRepository;
class ComposerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        view()->composer(
           '*','App\Http\ViewComposers\TranslationsComposer'
        );
    }

    public function register()
    {
      //
    }
}

{{translations.brand}} .

Laravel https://laravel.com/docs/5.1/views

0

lang.

1. .php App\Helpers. ( .php) Helper ServiceProvider. HelperServiceProvider , :

public function register()
    {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }

    }

2. , :

if(! function_exists('my_trans')){
    function my_trans($key){
        // load all the lang variable as an array here which should look like as below
        $lang = [
            'key1'=>'value1',
            'key2'=>'value2',
            'key3'=>'value3',
            'key4'=>'value4',
            'key5'=>'value5'
        ];

        return $lang[$key];
    }
}

3: , :

{{my_trans('key2')}}

.

0

Source: https://habr.com/ru/post/1649775/


All Articles