【发布时间】:2018-01-09 02:40:04
【问题描述】:
我阅读了Retrieving Translation Strings 上的翻译字符串文档,但不知何故我不明白如何应用它。
假设我想在视图posts.index 中呈现消息“我喜欢编程” 用英语、德语(“Ich mag Programmieren”)或西班牙语(“Me encanta programar”),取决于 App::setLocale() 设置的本地化。
翻译文件的外观如何?如何设置视图?
【问题讨论】:
我阅读了Retrieving Translation Strings 上的翻译字符串文档,但不知何故我不明白如何应用它。
假设我想在视图posts.index 中呈现消息“我喜欢编程” 用英语、德语(“Ich mag Programmieren”)或西班牙语(“Me encanta programar”),取决于 App::setLocale() 设置的本地化。
翻译文件的外观如何?如何设置视图?
【问题讨论】:
我终于明白了这个概念。在resources/lang 中,您可以为每种语言创建一个翻译 JSON 文件,例如。 g.:
/resources
/lang
/de.json
/es.json
没有必要创建en.json 文件,因为如果您不使用App::setLocale() 设置语言,en 将是默认语言。
de.json:
{
"I love programming.": "Ich mag programmieren."
}
es.json:
{
"I love programming.": "Me encanta programar."
}
接下来,您通过App::setLocale(); 在控制器中设置语言,现在有趣的部分来了。在视图中,您只包含 JSON 的键,例如。 G。
{{ __('I love programming.') }}
根据您的本地化,Laravel 会自动加载正确的翻译。
【讨论】:
我建议不要使用翻译字符串,而是使用键:
main-screen.dialog.add-item-button - 您知道这是主屏幕上的一个按钮。这比使用字符串 Add Item 要好得多。Abort、Add item、Alabama、Alaska、All、Arizona、.. Hello world. 更改为Hello world!,您不必更新所有文件。 【讨论】:
将您的语言文件存储在resources/lang 中,结构将是这样的。
/resources
/lang
/en
messages.php
/es
messages.php
所有语言文件都只返回一个键控字符串数组。例如:
<?php
return [
'welcome' => 'Welcome to our application'
];
然后,您必须定义捕获您的语言环境并设置它的路线。像这样
Route::get('welcome/{locale}', function ($locale) {
App::setLocale($locale);
// your code here
});
然后只需使用dot notation 打印{{ __() }} 或使用@lang()
{{ __('messages.welcome') }}
<!-- OR -->
@lang('messages.welcome')
【讨论】: