SvelteKit: Load translation for non-active locale #189
-
Hi Ivan I am trying to translate the url slugs for a multilingual SvelteKit page. Let's say on the German blog index page I have a language switcher which points to "/de/blog" and "/fr/blogue". I can access translations for the current locale with the $LL store and that works fine for pages within a locale. So by invoking, say, But how would I access the translation for a different locale than the current one in order to create links that point to the correct url in the target language? I was thinking of a language switcher that would take visitors to Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Hi @freeform99, import { i18n } from '$i18n/i18n-util'
import { loadAllLocales } from '$i18n/i18n-util.sync'
loadAllLocales() // you need to load all locales into memory before initializing
const L = i18n() // create a `L` instance
L.de.blog_title()
L.en.blog_title()
L.fr.blog_title() But keep in mind, that depending on where in your code you are doing that, it could potentially load the whole dictionary for all locales inside the browser of your users. Or you could create an Let me know if this helps :) |
Beta Was this translation helpful? Give feedback.
-
Hey @ivanhofer, I tried writing my own await Promise.all(locales.map((locale) => loadNamespaceAsync(locale, "meta"))); The problem is that it seems like the "main" namespace of a locale has to be loaded to successfully load further namespaces:
My first try at a workaround breaks loading the complete locale afterwards because then the object is already set 🤔 locales.forEach((locale) => {
if (!loadedLocales[locale]) {
loadedLocales[locale] = {};
}
}); Do you have an idea how to solve this? |
Beta Was this translation helpful? Give feedback.
Hi @freeform99,
you almost guesst the correct syntax ;)
The generated
src/i18n.util.ts
file, also includes ai18n
object which you can use to create anL
instance (it is not a svelte store, so you can't use the$
prefix).on the
L
instance you then have access to all locales and their translations.But keep in mind, that depending on where in your code you are doing that, it could potentially load the whole dictionary for…