在 Laravel 6、Module 中的本地化文件从 php 转换为 json (由于 Module 不支持,决定放弃)
1、现在翻译字符串都存放在 resources/lang 目录下的文件里。在此目录中,但凡应用支持的每种语言都应该有一个对应的子目录:
1 2 3 4 5 6 | /resources /lang /en validation.php /en-US validation.php |
2、之前的调用方法:return trans(‘online_store_theme_graphql::validation.custom.theme_editor_session.theme_editor_session_id_exists_rule’);
3、计划翻译文件以 JSON 格式存储在 resources/lang 目录中
1 2 3 4 5 6 7 8 | /resources /lang /en validation.php /en-US validation.php en.json en-US.json |
3、特意将 /en/validation.php 与 en.json 进行区分,以确认优先级的顺序。确认 .php 的优先级高于 .json。如图1
1 2 3 4 5 6 7 8 9 10 11 | <?php return [ 'custom' => [ 'theme_editor_session' => [ 'theme_editor_session_id_exists_rule' => 'The selected :attribute is invalid.' , ], ], 'attributes' => [], ]; |
1 2 3 | { "validation.custom.theme_editor_session.theme_editor_session_id_exists_rule": "The selected :attribute is invalid1." } |
4、删除掉 php 相关的目录与文件
1 2 3 4 | /resources /lang en.json en-US.json |
5、发现翻译未正常工作。如图2
6、使用 App Facade 的 getLocale 和 isLocale 方法确定当前的区域设置
1 2 | echo App::getLocale(); exit ; |
1 2 3 4 | { "error": {}, "text": "en" } |
7、参考 How to use json translation files using modules? (Translation Strings As Keys):https://github.com/nWidart/laravel-modules/issues/954 。调整服务提供者中的 registerTranslations(),删除掉对于 PHP 文件的引用,采用对于 JSON 文件的引用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * Register translations. * * @return void */ public function registerTranslations() { $langPath = resource_path( 'lang/modules/' . $this ->moduleNameLower); if ( is_dir ( $langPath )) { $this ->loadTranslationsFrom( $langPath , $this ->moduleNameLower); $this ->loadJsonTranslationsFrom( $langPath ); } else { $this ->loadTranslationsFrom(__DIR__ . '/../Resources/lang' , $this ->moduleNameLower); $this ->loadJsonTranslationsFrom(__DIR__ . '/../Resources/lang' ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /** * Register translations. * * @return void */ public function registerTranslations() { $langPath = resource_path( 'lang/modules/' . $this ->moduleNameLower); if ( is_dir ( $langPath )) { $this ->loadJsonTranslationsFrom( $langPath ); } else { $this ->loadJsonTranslationsFrom(__DIR__ . '/../Resources/lang' ); } } |
8、翻译仍然不能够正常工作。最终决定暂且放弃此实现。
近期评论