lib
lib copied to clipboard
Translations in stores and objects does not change when locale is changed
When i change locale like this locale.set(newLocale)
, the translations change only in some places. If i have translations in some store, they do not change. I have layout store which has setHeader method and if i call it like this setHeader({ title: $t('settings.title') });
and then change locale, this tranlations does not change (until page is refreshed).
Same problem is happening when I create array of objects and key in this object is translation, when i render components from this object, the translations will not update after locale change.
Object example:
const navItems= [
{
label: $t('home.title'),
target: '/home',
},
{
label: $t('about.title'),
target: '/about',
},
]
Usage example:
{#each navItems as item}
<NavButton
{...item}
/>
{/each}
In NavButton i am using the passed prop like this: <span>{label}</span>
I think that it realtime translates only things in svelte component it html section within $t()
function, but if you have translation stored somewhere else and in component you only want to render it without $t()
than it works only after page refresh, not on locale change
Not tested yet, but I’d try something like:
locale.subscribe(() => {
setHeader({ title: $t('settings.title') });
})
Yes this will work, but wouldnt it be better to implement it like in svelte-i18n? So that every translation no matter where or how it was defined, will translate when locale changes?
I am trying this same exact thing, but can't figure out how to get an array from $t
Can confirm that
locale.subscribe(()
Works.
That being said, +1 to this feature would be great to use like
const sample = [
{
label: $t('some.thing', 1),
value: 33,
},
{
label: $t('some.thing', 3),
value: 42,
},
]
or maybe even:
const sample = [
{
label: t.get('some.thing', 1),
value: 33,
},
{
label: t.get('some.thing', 3),
value: 42,
},
]
And have it update automatically. I can see how this would be quite complicated to implement but it would be useful when feeding dynamic data that has params and needs to be translated to a dropdown for example.
I think you should just use:
$: navItems = [
{
label: $t('home.title'),
target: '/home',
},
{
label: $t('about.title'),
target: '/about',
},
];
in your Svelte file..