All Projects → xiCO2k → laravel-vue-i18n

xiCO2k / laravel-vue-i18n

Licence: MIT license
Allows to connect your `Laravel` Framework translation files with `Vue`.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to laravel-vue-i18n

Laragym
A laravel gym management system
Stars: ✭ 130 (-69.77%)
Mutual labels:  laravel-framework
Pingcrm React
⚛️ Ping CRM React - A demo app to illustrate how Inertia.js works with Laravel and React (hosted on a heroku free dyno).
Stars: ✭ 158 (-63.26%)
Mutual labels:  laravel-framework
Laravel Auth
Laravel 8 with user authentication, registration with email confirmation, social media authentication, password recovery, and captcha protection. Uses offical [Bootstrap 4](http://getbootstrap.com). This also makes full use of Controllers for the routes, templates for the views, and makes use of middleware for routing. The project can be stood u…
Stars: ✭ 2,692 (+526.05%)
Mutual labels:  laravel-framework
Laravel Tutorial
Laravel 中文新手书籍《Laravel 入门教程》的源代码
Stars: ✭ 136 (-68.37%)
Mutual labels:  laravel-framework
Olaindex
✨ Another OneDrive Directory Index
Stars: ✭ 2,061 (+379.3%)
Mutual labels:  laravel-framework
Laravel Cheat Sheet
Additional resource for the Udemy Laravel Essentials course
Stars: ✭ 194 (-54.88%)
Mutual labels:  laravel-framework
Laravel Form Builder
Laravel Form builder for version 5+!
Stars: ✭ 1,601 (+272.33%)
Mutual labels:  laravel-framework
Laravel Gitscrum
GitScrum is a Project Management Tool, developed to help entrepreneurs, freelancers, managers, and teams Skyrocket their Productivity with the Agile methodology and Gamification.
Stars: ✭ 2,686 (+524.65%)
Mutual labels:  laravel-framework
Laravel Api Templates
Laravel API starter kit collection using different structures.
Stars: ✭ 149 (-65.35%)
Mutual labels:  laravel-framework
Learn Laravel
Laravel 学习资料和开源项目集
Stars: ✭ 229 (-46.74%)
Mutual labels:  laravel-framework
Laravel 5.3 And Vue Js 2.0 Social Network
Social network built with Laravel 5.3 and Vue js 2.0
Stars: ✭ 137 (-68.14%)
Mutual labels:  laravel-framework
Employee Mgmt Laravel5.4 Adminlte
The project is using laravel 5.4 and adminlte
Stars: ✭ 141 (-67.21%)
Mutual labels:  laravel-framework
Blogetc
Easily add a full Laravel blog (with built in admin panel and public views) to your laravel project with this simple package.
Stars: ✭ 198 (-53.95%)
Mutual labels:  laravel-framework
Blade
Use Blade templates without the full Laravel framework
Stars: ✭ 132 (-69.3%)
Mutual labels:  laravel-framework
Auth Tests
Always-current tests for Laravel's authentication system. Curated by the community.
Stars: ✭ 230 (-46.51%)
Mutual labels:  laravel-framework
Laravel Social Email Authentication
Laravel 5.3 bootstrap app with Multi Auth, Social and Email Authentication. Google re-Captcha, Facebook, Twitter, G+ and much more..
Stars: ✭ 129 (-70%)
Mutual labels:  laravel-framework
Xpressengine
PHP Open Source CMS
Stars: ✭ 178 (-58.6%)
Mutual labels:  laravel-framework
Laravel User Activity
Monitor user activity easily!
Stars: ✭ 253 (-41.16%)
Mutual labels:  laravel-framework
Laracrud
Laravel Code Generator based on MySQL Database
Stars: ✭ 238 (-44.65%)
Mutual labels:  laravel-framework
Wagonwheel
Offer an online version of your Laravel emails to users.
Stars: ✭ 224 (-47.91%)
Mutual labels:  laravel-framework

Laravel Vue i18n

GitHub Workflow Status (master) License Version Total Downloads

laravel-vue-i18n is a Vue3 plugin that allows to connect your Laravel Framework translation files with Vue. It uses the same logic used on Laravel Localization.

Installation

With npm:

npm i laravel-vue-i18n

or with yarn:

yarn add laravel-vue-i18n

Setup

If you want to see a screencast on how to setup check out this video: How to use Laravel Vue i18n plugin.

With Vite

import { createApp } from 'vue'
import { i18nVue } from 'laravel-vue-i18n'

createApp()
    .use(i18nVue, {
        resolve: async lang => {
            const langs = import.meta.glob('../../lang/*.json');
            return await langs[`../../lang/${lang}.json`]();
        }
    })
    .mount('#app');

SSR (Server Side Rendering)

For Server Side Rendering the resolve method should not receive a Promise and instead take advantage of the globEager method like this:

.use(i18nVue, {
    lang: 'pt',
    resolve: lang => {
        const langs = import.meta.globEager('../../lang/*.json');
        return langs[`../../lang/${lang}.json`].default;
    },
})

PHP Translations Available on Vue

In order to load php translations, you can use this Vite plugin.

// vite.config.js
import i18n from 'laravel-vue-i18n/vite';

export default defineConfig({
    plugins: [
        laravel([
            'resources/css/app.css'
            'resources/js/app.js',
        ]),
        vue(),

        // Laravel >= 9
        i18n(),

        // Laravel < 9, since the lang folder is inside the resources folder
        // you will need to pass as parameter:
        // i18n('resources/lang'),
    ],
});

During the npm run dev execution time, the plugin will create some files like this php_{lang}.json on your lang folder. And to avoid that to be commited to your code base, I suggest to your .gitignore this like:

lang/php_*.json

With Webpack / Laravel Mix

import { createApp } from 'vue'
import { i18nVue } from 'laravel-vue-i18n'

createApp()
    .use(i18nVue, {
        resolve: lang => import(`../../lang/${lang}.json`),
    })
    .mount('#app');

SSR (Server Side Rendering)

For Server Side Rendering the resolve method should receive a require instead of a Promise:

.use(i18nVue, {
    lang: 'pt',
    resolve: lang => require(`../../lang/${lang}.json`),
})

PHP Translations Available on Vue

In order to load php translations, you can use this Mix plugin.

const mix = require('laravel-mix');
require('laravel-vue-i18n/mix');

// Laravel >= 9
mix.i18n();

// Laravel < 9, since the lang folder is inside the resources folder
// you will need to pass as parameter:

// mix.i18n('resources/lang');

Usage

<template>
    <div>
        <h1>{{ $t('Welcome, :name!', { name: 'Francisco' }) }}. </h1>
        <div>Logged in {{ $tChoice('{1} :count minute ago|[2,*] :count minutes ago', 10) }}</div>
    </div>
</template>

Plugin Options

  • lang (optional): If not provided it will try to find from the <html lang="pt"> tag.
  • fallbackLang (optional): If the lang was not provided or is invalid, it will try reach for this fallbackLang instead, default is: en.
  • resolve (required): The way to reach your language files.
  • shared (optional): Whether to share the same I18n instance between different Vue apps, default is: true.
  • onLoad (optional): It's called everytime a language is loaded.
createApp().use(i18nVue, {
    lang: 'pt',
    resolve: lang => import(`../../lang/${lang}.json`),
})

trans(message: string, replacements: {})

The trans() method can translate a given message.

// lang/pt.json
{
    "Welcome!": "Bem-vindo!",
    "Welcome, :name!": "Bem-vindo, :name!"
}

import { trans } from 'laravel-vue-i18n';

trans('Welcome!'); // Bem-vindo!
trans('Welcome, :name!', { name: 'Francisco' }) // Bem-vindo Francisco!
trans('Welcome, :NAME!', { name: 'Francisco' }) // Bem-vindo FRANCISCO!

wTrans(message: string, replacements: {})

The wTrans() same as trans() but returns a reactive obj with translated value, use it instead of trans() to watch any changes (language changes or lang files loaded) and set the new value.

// lang/pt.json
{
    "Welcome!": "Bem-vindo!",
    "Welcome, :name!": "Bem-vindo, :name!"
}

import { wTrans } from 'laravel-vue-i18n';

setup() {
    return {
        welcomeLabel: wTrans('Welcome!'),
        welcomeFrancisco: wTrans('Welcome, :name!', { name: 'Francisco' })
    }
}

<template>
    <div>{{ welcomeLabel }}</div> // <div>Bem-vindo!</div>
    <div>{{ welcomeFrancisco }}</div> // <div>Bem-vindo, Francisco!</div>
</template>

transChoice(message: string, count: number, replacements: {})

The transChoice() method can translate a given message based on a count, there is also available an trans_choice alias, and a mixin called $tChoice().

// lang/pt.json
{
    "There is one apple|There are many apples": "Existe uma maça|Existe muitas maças",
    "{0} There are none|[1,19] There are some|[20,*] There are many": "Não tem|Tem algumas|Tem muitas",
    "{1} :count minute ago|[2,*] :count minutes ago": "{1} há :count minuto|[2,*] há :count minutos"
}

import { transChoice } from 'laravel-vue-i18n';

transChoice('There is one apple|There are many apples', 1); // Existe uma maça
transChoice('{0} There are none|[1,19] There are some|[20,*] There are many', 19); // Tem algumas
transChoice('{1} :count minute ago|[2,*] :count minutes ago', 10); // Há 10 minutos.

wTransChoice(message: string, count: number, replacements: {})

The wTransChoice() same as transChoice() but returns a reactive obj with translated value, use it instead of transChoice() to watch any changes (language changes or lang files loaded) and set the new value.

// lang/pt.json
{
    "There is one apple|There are many apples": "Existe uma maça|Existe muitas maças",
    "{0} There are none|[1,19] There are some|[20,*] There are many": "Não tem|Tem algumas|Tem muitas",
    "{1} :count minute ago|[2,*] :count minutes ago": "{1} há :count minuto|[2,*] há :count minutos"
}

import { wTransChoice } from 'laravel-vue-i18n';

setup() {
    return {
        oneAppleLabel: wTransChoice('There is one apple|There are many apples', 1),
        multipleApplesLabel: wTransChoice('{0} There are none|[1,19] There are some|[20,*] There are many', 19)
    }
}

<template>
    <div>{{ oneAppleLabel }}</div> // <div>Existe uma maça</div>
    <div>{{ multipleApplesLabel }}</div> // <div>Tem algumas</div>
</template>

loadLanguageAsync(lang: string)

The loadLanguageAsync() can be used to change the location during the runtime.

import { loadLanguageAsync } from 'laravel-vue-i18n';

<template>
    <div>{{ $t('Welcome!') }}</div>
    <button @click="loadLanguageAsync('pt')">Change to Portuguese Language</button>
</template>

getActiveLanguage()

The getActiveLanguage() returns the language that is currently being used.

import { getActiveLanguage } from 'laravel-vue-i18n';

const lang = getActiveLanguage(); // en

isLoaded(lang?: string)

The isLoaded() method checks if the language is loaded. If the lang parameter is not passed it will check for the actual language set.

import { isLoaded } from 'laravel-vue-i18n';

const loaded = isLoaded(); // true
const loaded = isLoaded('fr'); // false

Using multiple instances

Under the hood, the Vue plugin is using a I18n class which encapsulates all the translation logic and the currently active language. This means that it's possible to create multiple class instances, each with different options and active language. This can be useful for scenarios where part of the app needs to be translated to a language different from the main UI.

Note that loaded languages are still shared between different instances. This avoids loading the same set of translations multiple times. The main difference between different instances will be the currently active language.

import { I18n } from 'laravel-vue-i18n'

const resolver = lang => import(`./fixtures/lang/${lang}.json`)

const i18nEn = new I18n({
    lang: 'en',
    resolve: resolver
})
const i18nPt = new I18n({
    lang: 'pt',
    resolve: resolver
})

i18nEn.trans('Welcome!') // will output "Welcome!"
i18nPt.trans('Welcome!') // will output "Bem-vindo!"

By default, installing the the i18nVue plugin will create a shared instance. This instance is accessed when importing the translation functions, such as trans, directly. When using multiple Vue app instances, it's possible to either share the I18n instance between them, or have each app create its own instance.

Shared usage (default) - all Vue app instances will use the same I18n class and currently active language:

import { i18nVue } from 'laravel-vue-i18n'

const appA = createApp()
    .use(i18nVue, { lang: 'pt' })
    .mount('#app-1');

const appB = createApp()
    .use(i18nVue)
    .mount('#app-2');

// elsewhere
import { trans } from 'laravel-vue-i18n'

trans('Welcome!') // will output "Bem-vindo!"

Non-shared usage - each Vue app will have its own I18n instance & currently active language.

import { i18nVue } from 'laravel-vue-i18n'

const appA = createApp()
    .use(i18nVue, {
        lang: 'es'
        shared: false, // don't use the shared instance
    })
    .mount('#app-1');

const appB = createApp()
    .use(i18nVue, {
        lang: 'pt'
        shared: false, // don't use the shared instance
    })
    .mount('#app-2');

Accessing the shared instance

It's possible to access the shared instance via code as well:

import { I18n } from 'laravel-vue-i18n'

I18n.getSharedInstance()

Caveats

It is possible to import a translation function before installing the i18nVue plugin. When calling the translation function, ie trans(), and the plugin has not been installed, a shared I18n instance will be created with default options. This ensures that it's possible to import and call these functions without any fatal errors. However, this may yield undesired results. Therefore, it is advisable to never call any translation methods before the plugin is installed.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].