Dom
Dom

Reputation: 3444

Which syntax to use to translate in Blade files?

I am using Laravel 8 and I want to translate a website. As I have a lot of translations to do, I will use the "translations strings as key" (please see Laravel documentation).

I can use the following two methods in my Blade files.

{{ __('A propos') }}

OR

@lang('A propos')

My question is: what method do you use and why?

Upvotes: 4

Views: 4295

Answers (2)

Muhammad Atif Akram
Muhammad Atif Akram

Reputation: 1315

I'd really prefer using the __ helper function. If you go in-depth then you will find this helper function pretty cool in terms of its functionality and flexibility. Other than the translation string it receives 2 other parameters. One is replace[] and other is locale.

if (! function_exists('__')) {
/**
 * Translate the given message.
 *
 * @param  string|null  $key
 * @param  array  $replace
 * @param  string|null  $locale
 * @return string|array|null
 */
function __($key = null, $replace = [], $locale = null)
{
    if (is_null($key)) {
        return $key;
    }

    return trans($key, $replace, $locale);
 }
}

So we can use this function to perform translation using the key and in bonus also to replace the translation with the values passed in 2nd parameter. Not only that, but we also have the option to specify in which language we need the translation in the 3rd parameter.

Secondly, we can use this function anywhere in the project either in Laravel Controllers , views etc.

On the other side, we have the blade directive @lang(). I couldn't find its definition anywhere in the vendor but I'm sure that you can only use this in your blade templates. Further it has no replace[] and locale parameter flexibility just like the __() helper function.

At the end of the debate, I'll really choose __() helper function because it is flexible, reusable and good documented.

Upvotes: 3

Top-Master
Top-Master

Reputation: 8745

For anyone who needs best combo of said approaches (like me), simply use @tr(...) directive, like:

@tr('My :app says hello!', ['app' => env('APP_NAME')])

But for above to function, in your AppServiceProvider.php file (in app/Providers directory) do something like:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('tr', function ($expression) {
            return "<?php echo __($expression); ?>";
        });
    }
}

PhpStorm

Once the directive is created, enable auto-completion:

  1. In IDE Settings, Go to Languages & Frameworks > PHP > Blade.

  2. There disable the checkbox Use default settings.

  3. Then switch to the Directives tab, and add new directive, with settings:

    • Name: tr
    • Prefix: <?php echo __(
    • Suffix: ); ?>

Upvotes: 2

Related Questions