genl/matice

在JavaScript中使用您的Laravel翻译。生成一个Blade指令,导出所有Laravel翻译,并在JavaScript中提供漂亮的trans()辅助函数。

1.1.9 2024-03-30 22:23 UTC

This package is auto-updated.

Last update: 2024-08-30 23:17:17 UTC


README

Latest Version on Packagist Latest Version on NPM Tests Total Downloads on packagist Downloads on NPM

Logo

https://github.com/genl/matice/actions/workflows/.github/workflows/tests.yml/badge.svg?event=push

Matice创建了一个Blade指令,您可以在视图中包含它。它将导出一个JavaScript对象,其中包含您Laravel应用程序的翻译,键名为它们的名字(别名、语言、文件名、文件夹名),以及全局的trans()、__()和transChoice()辅助函数,您可以使用它们在JavaScript中访问您的翻译。

安装

您可以通过composer安装此包

composer require genl/matice
  1. 在主应用程序JavaScript加载之前,在模板中的某个位置包含我们的Blade指令(@translations)——可能在页眉中。
  2. 如果您想自定义配置,请发布供应商
php artisan vendor:publish --provider="Genl\Matice\MaticeServiceProvider"

Matice作为NPM matice包提供,该包公开了trans()函数,用于在前端应用程序中使用,这些应用程序不使用Blade。您可以使用以下命令安装NPM包

// With yarn
yarn add matice

With npm
npm install matice

或从CDN加载

<!-- Load the Matice translation object first -->
<script src="https://unpkg.com/matice@1.1.x/dist/matice.min.js" defer></script>
  • 请注意,JavaScript包仅包含翻译逻辑。您必须生成翻译文件并使其可供前端应用程序使用。Blade指令@translations会在您刷新页面时为您完成。

TypeScript支持

Matice完全用TypeScript编写,因此它与TypeScript项目兼容。

用法

  • 核心概念

Matice几乎与Laravel相同的本地化概念。更多关于Laravel本地化的信息。

此包使用@translations指令来注入一个JavaScript对象,其中包含所有应用程序的翻译,键名为它们的名称。此集合在客户端全局上在window.Matice对象中可用。@translations指令接受一个数组或逗号分隔的字符串形式的区域列表。如果没有提供区域,将加载所有翻译。

示例

按如下方式导入trans()函数

@translations(['en', 'fr'])

or

@translations('en, fr')

该包还创建了一个可选的trans() JavaScript辅助工具,它的工作方式与Laravel的PHP trans()辅助工具类似,用于检索翻译字符串。

示例

按如下方式导入trans()函数

import { trans } from "matice";

假设我们有一个这样的翻译文件

// resources/lang/en/custom.php

return [
    'greet' => [
        'me' => 'Hello!',
        'someone' => 'Hello :name!',
        'me_more' => 'Hello Ekcel Henrich!',
        'people' =>'Hello Ekcel!|Hello everyone!',
    ],
    'balance' => "{0} You're broke|[1000, 5000] a middle man|[1000000,*] You are awesome :name, :count Million Dollars"
];
// resources/lang/fr/custom.php

return [
    'greet' => [
        'me' => 'Bonjour!'
    ]
];

trans

检索文本

let sentence = ''

sentence = trans('greet.me') // Hello!

// With parameters
sentence = trans('greet.someone', {args: {name: "Ekcel"}}) // Hello Ekcel!

更新区域设置

Matice公开了setLocale函数来更改trans函数使用的区域。

import { setLocale } from "matice"

// update the locale
setLocale('fr')
const sentence = trans('greet.me') // Bonjour!

复数

在复数方面,选择取决于count参数。要启用复数,请将参数pluralize传递给true。

// Simple pluralization
sentence = trans('greet.people', {args: {count: 0}, pluralize: true}) // Hello Ekcel!
sentence = trans('greet.people', {args: {count: 2}, pluralize: true}) // Hello everyone!

// Advanced pluralization with range. Works the same way.
// [balance => '{0} You're broke|[1000, 5000] a middle man|[1000000,*] You are awesome :name, :count Million Dollars']
sentence = trans('balance', {args: {count: 0}, pluralize: true}) // You're broke
sentence = trans('balance', {args: {count: 3000}, pluralize: true}) // a middle man

选择翻译

Matice提供了一个复数辅助函数

import { transChoice } from "matice"

let sentence = transChoice('balance', 17433085, {name: 'Ekcel'}) // You are awesome Ekcel, 17433085 Million Dollars

下划线函数

  • 以及trans()函数一样,Matice还提供了__(),它的工作方式与trans()函数类似,但具有以下特点:当键未找到时不会抛出错误,而是返回键本身。

transChoice()始终在键未找到时抛出错误。要更改此行为,请使用__(key, {pluralize: true})

sentence = trans('greet.unknown') // -> throws an error with a message.
sentence = __('greet.unknown') // greet.unknown

默认值

Matice 使用您当前应用的地区设置 app()->getLocale() 作为默认地区来生成带有 blade 指令 @translations 的翻译对象。使用命令行生成时同样适用。

当 Matice 找不到密钥时,它会回退到默认地区并再次搜索。回退是您在 config.app.fallback_locale 中定义的相同地区。

// config/app.php

'locale' => 'fr',
'fallback_locale' => 'en',

检索当前区域设置

Matice 公开了 MaticeLocalizationConfig 类。

import { MaticeLocalizationConfig } from "matice"

const locale = MaticeLocalizationConfig.locale // 'en'

const fallbackLocale = MaticeLocalizationConfig.fallbackLocale // 'en'

const locales = MaticeLocalizationConfig.locales // ['en', 'fr']

Matice 还提供了处理地区信息的辅助工具。

import { setLocale, getLocale, locales } from "matice"

// Update the locale
setLocale('fr') //

const locale = getLocale() // 'fr'

const locales = locales() // ['en', 'fr']

强制区域设置

从版本 1.1.4 开始,可以在不更改全局地区的情况下强制为特定翻译设置地区。

setLocale('en') // Set the current locale to English.

trans('greet.me') // "Hello!"
trans('greet.me', { locale: 'fr' }) // "Bonjour!"
trans('greet.me', { args: {}, locale: 'fr' }) // "Bonjour!"

__('greet.me', { locale: 'fr' }) // "Bonjour!"

transChoice('greet.me', 1, undefined, 'fr') // "Bonjour!"
transChoice('greet.me', 1, {}, 'fr') // "Bonjour!"

过滤翻译

Matice 支持过滤它提供给 JavaScript 的翻译,这对于控制数据大小非常有用,因为当翻译行数达到数千行时,翻译可能会变得过大。

过滤命名空间

要设置命名空间翻译过滤,请在配置文件中更新 onlyexcept 设置,将其作为翻译文件夹或文件的数组。注意:如果同时在 'only' 和 'except' 中设置相同的命名空间,则结果为 'except'。但在其他情况下,'only' 优先于 'except'。

    // config/matice.php
    
    return [
        // Export only 
        'only' => [
            'fr/', // Take all the 'fr' directory with his children
            'es', // Take all the 'es' directory with his children
            'en/auth', // With or without the file extension
            'en/pagination.php',
            'en/validations',
        ],
        
        // Or... export everything except
        'except' => [
            'en/passwords',
            'en\\validations',
        ],
    ]; 

基本目录是在配置文件中定义的 lang_directory: config('matice.lang_directory')

与SPA一起使用

Matice 注册了一个 Artisan 控制台命令来生成 matice_translations.js 翻译文件,该文件可以作为资产管道的一部分使用(或不用),例如 Laravel Mix

您可以在项目中运行 php artisan matice:generate --no-export 来生成一个静态翻译文件,而不在 resources/assets/js/matice_translations.js 中的导出语句。您可以在 config/matice.php 文件中自定义生成路径。

php artisan matice:generate --no-export

matice_translations.js 的一个示例,其中 auth 翻译位于 resources/lang/en/auth.php 中。

// resources/lang/en/auth.php

return [
    'failed' => 'These credentials do not match our records.',
    'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
];
// matice_translations.js

const Matice = {
    locale: 'en',
    fallbackLocale: 'en',
    translations: {
      en: {
        auth: {
          failed: 'These credentials do not match our records.',
          throttle: 'Too many login attempts. Please try again in :seconds seconds.'
        }
      }
    }
};

此时,您可以在 JavaScript 中像通常一样使用此翻译文件,并将其粘贴到您的 HTML 中。

这对于您的 Laravel 和 JS 应用程序分离(如 SPA 或 PWA)很有用。因此,您可以与您的 JS 应用程序链接生成的翻译文件。如果您不是 SPA、WPA 等情况,您可能永远不需要手动生成翻译,因为 @translations 指令在应用程序环境为 'production' 时已经为您完成了,这可以提高性能。

<!-- Manually include the generated translations in your HTML file. -->

<html>
<head>
    <title></title>
    
    <!-- The matice package -->
    <script src="https://unpkg.com/matice@1.1.x/dist/matice.min.js" defer></script>

    <!-- "link to the generated translations file" -->
    <script src="https://your-awesomeapp-server.co/matice_translations.js"></script>
</head>

<body>
    😃
</body>
</html>

每当您的翻译消息更改时,再次运行 php artisan matice:generate。请记住禁用浏览器缓存,因为它可能已缓存旧的翻译文件。

与Vue组件一起使用

基本上,Matice 可以集成到任何 JavaScript 项目中。即使是像 Vue.js、React.js 或 Angular 这样的大型框架。一些框架(如 Vue)会动态地重新渲染 UI。在本节中,我们将向您展示如何将 Matice 与 Vue 2 绑定。基于此示例,我们假设您可以根据您用于项目的框架进行类似操作。例如,使用 React,您应该在调用 setLocale() 后重新渲染整个应用程序,以便更改可见。

将其添加到您的 app.js 文件中。

// app.js

import {__, trans, setLocale, getLocale, transChoice, MaticeLocalizationConfig, locales} from "matice"

Vue.mixin({
    methods: {
        $trans: trans,
        $__: __,
        $transChoice: transChoice,
        $setLocale(locale: string) {
            setLocale(locale);
            this.$forceUpdate() // Refresh the vue instance(The whole app in case of SPA) after the locale changes.
        },
        // The current locale
        $locale() {
            return getLocale()
        },
        // A listing of the available locales
        $locales() {
            return locales()
        }
    },
})

然后您可以在 Vue 组件中使用这些方法。

<p>{{ $trans('greet.me') }}</p>

深入了解

Matice 扩展了 Laravel 的 Translator 类。使用 Translator::list() 返回应用程序所有翻译的数组表示。

如果您只想加载特定地区的翻译,请使用 matice 门面。

use GENL\Matice\Facades\Matice;

// Loads all the translations
$translations = Matice::translations();

// Or loads translations for a specific locale.
$translations = Matice::translations($locale);

基于环境的 minified matice 辅助文件加载

当使用 @translations Blade 指令时,Matice 会检测当前环境,并在 APP_ENVproduction 时最小化输出。

在开发中,@translations 在每次页面重新加载时都会循环到 lang 目录以生成 matice 对象,并且不会生成 matice_translations.js 文件。在生产中,@translations 在应用程序首次打开时为您生成 matice_translations.js 文件,然后每次页面重新加载时都使用生成的文件。由于 Matice 对象不是每次都生成,因此在生产中没有性能影响。此行为可以在 config/matice.php 文件中禁用,将 use_generated_translations_file_in_prod 设置为 false。

#### 注意:Matice 支持同时使用 json 翻译文件和 php 文件。

测试

// --  laravel test --
composer test

// -- js test --

// With yarn
yarn test

// With npm
npm run test

变更日志

请参阅变更日志获取最近更改的更多信息。

贡献

请参阅贡献指南以获取详细信息。

安全性

如果您发现任何与安全相关的问题,请通过电子邮件bigcodole@gmail.com联系,而不是使用问题跟踪器。

致谢

许可协议

MIT 许可协议 (MIT)。请参阅许可文件以获取更多信息。

Laravel 包模板

本软件包是用Laravel 包模板生成的。