aw-studio/laravel-json-translations

v0.2 2022-11-25 09:05 UTC

This package is auto-updated.

Last update: 2024-09-25 12:58:02 UTC


README

Laravel Json Translations 包提供了一种便捷的方式,通过一个提供 JSON 对象的 JavaScript 文件的路由,从 resources/lang 目录提供所有翻译,并自动将它们绑定到 window 对象。这对于在前端框架(如 Vue.js)中与 i18n 包一起工作非常有用。所有翻译将以以下格式提供

{
"en": {
    "auth": {
        "failed": "These credentials do not match our records.",
        "password": "The provided password is incorrect.",
        "throttle": "Too many login attempts. Please try again in :seconds seconds."
    }
}

安装

该包可以通过 composer 安装

composer require aw-studio/laravel-json-translations

用法

routes/web.php 中通过可用的助手函数注册将提供翻译文件的路线,该助手函数接受一个文件名和一个包含文件中应包含的所有语言环境的数组作为参数

// routes/web.php

use AwStudio\LaravelJsonTranslations\Facades\JsonTranslations;

// this will serve https://your-app.com/my-translations.js
JsonTranslations::javascript('my-translations', ['en', 'de']);

现在您可以使用 <script> 标签包含本地 JavaScript,或者在需要提供 JSON 翻译的视图中简单地使用 blade 指令

// will render to <script src="/my-translations.js"></script>
@translations('my-translations')

如果您想在 API 中接收原始 JSON,可以使用 JsonTranslations 门面中的 json 方法实现

use AwStudio\LaravelJsonTranslations\Facades\JsonTranslations;

Route::get('json', function () {
    return JsonTranslations::json(['en', 'de']);
});

Vue i18n 示例

因为 JSON 翻译绑定到 window 对象

import Vue from 'vue';
import VueI18n from 'vue-i18n';

const messages = window.i18n;

Vue.use(VueI18n);

const i18n = new VueI18n({
    locale: 'de',
    fallbackLocale: 'en',
    messages
});

export default i18n;