为 Laravel 应用程序添加本地化支持,使用 PoEdit 和 Gettext

1.3.2 2016-03-01 00:51 UTC

README

Build Status

安装

Laravel 5.2 安装

将 composer 仓库添加到您的 composer.json 文件

"require": {
    "clusteramaryllis/gettext": "1.3.x"
}

然后运行 composer update。完成后,在 config/app.php 文件中的 providers 数组中注册服务提供者

'providers' => [

    // ...

    Clusteramaryllis\Gettext\GettextServiceProvider::class,

]

您还可以通过 aliases 数组提供静态语法

'aliases' => [

    // ...

    'Gettext' => Clusteramaryllis\Gettext\Facades\Gettext::class,

]

发布配置文件(可选)(将在 config/gettext.php 上创建)

php artisan vendor:publish

命令

可用命令

gettext:create => 生成新的 .po 文件

gettext:update => 更新现有的 .po 文件

可用选项

使用 php artisan gettext:create --helpphp artisan gettext:update --help 查看详细信息

示例

php artisan gettext:create --sources="app/Http/Controllers, resources/views" --destination="resources/locale" --locale="en_US" 

这将生成 resources/locale/en_US/LC_MESSAGES/messages.po 中的 .po 文件,并将扫描 app/Http/Controllersresources/views 上的任何使用 php-gettext 函数的字符串

完成后,您可以使用 PoEdit 等工具轻松地将应用程序翻译成其他语言。

如何使用

简单用法

  1. 使用 Gettext 方法或助手将字符串包裹在 view
<!-- resources\views\welcome.blade.php -->
{!! __('Welcome to main page') !!}
  1. 通过 config/gettext.php 文件中的语言数组添加您的语言偏好
languages => [

    // ...,

    'sv' => [
        'locale' => 'sv_SE',
        'encoding' => 'utf-8',
        'plural_forms' => "nplurals=2; plural=(n != 1);",
    ]      
]
  1. 运行 php artisan gettext:create。这将生成 app\Http\Controllersresources\views 中的 .po 文件(默认选项)
resources\locale\sv_SE\LC_MESSAGES\messages.po

& 准备扫描翻译字符串在 app\Http\Controllers & resources\views

  1. 使用 PoEdit 或类似编辑器打开 .po 文件。在 PoEdit 中,您需要点击更新以将扫描到的字符串填充到表中。之后,您就可以开始翻译了。

  2. 简单的路由测试

Route::get('/', function() {

    Gettext::bindTextDomain('messages', base_path('resources/locale'));
    Gettext::textDomain('messages');

    Gettext::setLocale(LC_ALL, 'sv_SE.utf-8');

    return view('welcome');
});

可用方法

更多详细的方法及其参数可以在 这里 查看。

鸣谢

本软件包受到 laravel-gettext 的启发,由 Nicolás Daniel Palumbo 为 .po 文件创建,并使用了 Danilo Segan 的 php-gettext 软件包。