'VueJS i18n - How to change the variable prefix in translation files

I'm doing an app using Laravel inertia and Vue, we wanted to add i18n to the app and use the same translation files for both laravel and i18n, the problem is the variable interpolation, laravel by default use :variable but vue i18n use {variable}

I tried to create a custom formatter based on what i've found here but using a custom formatter seems deprecated since I have this in my console: [intlify] Not supported 'formatter'.

I've seen on the official i18n doc that i18n is supposed to have an option for both prefix and suffix for the variable interpolation but it does not seems to exists in vue-i18n.

Does anyone ever experienced this or have an idea to solve this 'issue' ?



Solution 1:[1]

I run a for loop in my translation jsons and converted :variable syntax to {variable}

import {createI18n} from 'vue-i18n'
import zhCN from '../lang/zh-CN.json';

export function initializeI18n() {
    let en = {};

    Object.entries(zhCN).forEach(([key, value]) => {
        let newEnValue = key;
        en[key] = key;

        if (value.includes(':')) {
            let arr = value.match(/\B\:\w+/ig);
            arr.forEach(matchedStr => {
                let cleanMatchedStr = matchedStr.replace(':', '')
                value = value.replace(matchedStr, `{${cleanMatchedStr}}`)
                newEnValue = newEnValue.replace(matchedStr, `{${cleanMatchedStr}}`)
            })
            zhCN[key] = value;
            en[key] = newEnValue;
        }
    })

    return createI18n({
        locale: window.__DEFAULT_LOCALE__,
        fallbackLocale: window.__FALLBACK_LOCALE__,
        messages: {
            'zh-CN': zhCN,
            en
        },
        silentFallbackWarn: true,
        silentTranslationWarn: true
    });
}

This was, putting in es.js

"Hello :name": "Hola :name"

should work as expected:

{{ $t("Hello :name", {name: 'world'}) }},

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 senty