Reputation: 687
I read the documentation for translation strings on Retrieving Translation Strings but somehow I don't understand how to apply it.
Let's say I would like to render in a view posts.index
the message "I like programming" in English, German ("Ich mag Programmieren") or Spanish ("Me encanta programar"), depending on the localization set by App::setLocale().
How would the translation files look like and how would I setup the view?
Upvotes: 6
Views: 20391
Reputation: 2400
Messages (you can choose) is the name of your translation file.
For each language, you make a dir in the lang folder. Spanish is es.
{{ trans('messages.cool') }}
I hope this helps...
Upvotes: 1
Reputation: 1041
I'd recommend to stay away from using translation strings and use keys instead:
main-screen.dialog.add-item-button
- you know that this is a button on the main screen. This is much better than working with a string Add Item
.Abort
, Add item
, Alabama
, Alaska
, All
, Arizona
,.. Hello world.
to Hello world!
you don't have to update all your files. Upvotes: 13
Reputation: 687
I finally understood the concept. Within resources/lang
you create a translation JSON file for every language, e. g.:
/resources
/lang
/de.json
/es.json
There is no need to create an en.json
file as en
will be the default language if you don't set a language with App::setLocale()
.
de.json:
{
"I love programming.": "Ich mag programmieren."
}
es.json:
{
"I love programming.": "Me encanta programar."
}
Next, you set in your controller the language via App::setLocale();
and now comes the fun part. In the view, you only include the key of the JSON, e. g.
{{ __('I love programming.') }}
and depending on your localization, Laravel will automatically load the correct translation.
Upvotes: 13
Reputation: 4915
Store your language files within resources/lang
, and structure would be like this.
/resources
/lang
/en
messages.php
/es
messages.php
All language files simply return an array of keyed strings. For example:
<?php
return [
'welcome' => 'Welcome to our application'
];
Then you've to define your route where you capture your locale and set it. like this
Route::get('welcome/{locale}', function ($locale) {
App::setLocale($locale);
// your code here
});
And then simply use dot notation
to print with {{ __() }}
or use @lang()
{{ __('messages.welcome') }}
<!-- OR -->
@lang('messages.welcome')
Upvotes: 4