sveltekit-i18n / lib

Internationalization library built for SvelteKit.
MIT License
488 stars 31 forks source link

How to set a default or fallback key and language? #61

Closed ralyodio closed 2 years ago

ralyodio commented 2 years ago

I am needing a way to specify default language as "en" (if we don't have a language file for example). In addition I need a way to default the using the key if no entry exists.

For example I use "$t('Welcome')" as my key, if no language code file or no entry for "Welcome" exists it should just default to the key (which is "Welcome").

How do I do this?

ralyodio commented 2 years ago

so i found fallbackLocale:

export const config = {
  fallbackLocale: 'en',
  translations: {
    en: { lang },
    cs: { lang },
  },

Now I just need to be sure the key is used if an entry doesn't exist in a locale file.

ralyodio commented 2 years ago

just tested with a non existing locale "nl" and it doesnt' show english.

how to fix?

import i18n from 'sveltekit-i18n';

/** @type {import('sveltekit-i18n').Config} */
const config = {
    fallbackLocale: 'en',
    loaders: [
        {
            locale: 'en',
            key: '',
            loader: async () => (await import('./lang/en.json')).default
        },
        {
            locale: 'es',
            key: '',
            loader: async () => (await import('./lang/es.json')).default
        },
        {
            locale: 'de',
            key: '',
            loader: async () => (await import('./lang/de.json')).default
        },
        {
            locale: 'ja',
            key: '',
            loader: async () => (await import('./lang/ja.json')).default
        },
        {
            locale: 'ar',
            key: '',
            loader: async () => (await import('./lang/ar.json')).default
        }
    ]
};

export const rtl = ['ar'];

export const { t, locale, locales, loading, loadTranslations } = new i18n(config);
jarda-svoboda commented 2 years ago

Ok, fallbackLocale should work exactly like this.. I’ll check this for errors - tests throwing no errors - your config seems to be correct to me..

jarda-svoboda commented 2 years ago

It works fine when no translation key is present for given translation and it correctly fallbacks to fallbackLocale. The problem is when you provide unknown locale (undefined within your configuration = out of $locales store). in that case it does not fallbacks to fallbackLocale, but it does not set the locale at all (will be fixed in the next version)...

So for now, there is a workaround to setup a constraint for locale to be possibly changed to one of $locales...