This project supports multiple languages. Let's learn how to add a new language file to support various languages.
Add a lang file to the $lib/module/common/i18n/lang folder. The lang file should export an object of type LangFile.
export type LangFile = LayoutLangFile & PathLangFile
export interface SubLangFile{
[key: string]: string|SubLangFile
}
export interface PathLangFile{
[pathname: string]: SubLangFile
}
export interface LayoutLangFile{
layout?: {
[layoutName: string]: SubLangFile
};
}
// $lib/module/common/i18n/lang/ko.ts
const ko: LangFile = {
...
}
export default ko;
To include language information for layouts in a lang file, you can structure it like this:
const ko = {
layout: {
layout1: {
...
},
layout2: {
...
},
...
}
}
Each LangFile object may contain an object with the key layout. This layout object can contain sub-objects with layout names as the keys.
The sub-objects corresponding to each layout name can contain properties whose values are either string or repeating objects with string properties.
const ko = {
layout: {
layout1: {
header: '헤더',
aside: {
asideNewSong: {
foo:{
bar: '...'
},
...
},
...
}
},
...
}
}
The structure of the lang file for each page is as follows:
const ko = {
'/path': {
...// repeating string objects
},
'/path2': {
...// repeating string objects
}
}
To use the lang file in a layout, write the code as follows:
<script>
import i18n, {getLang} from '$lib/module/common/i18n/i18n';
const lang = getLang(); // For the top-level layout, use useLang() instead.
$: i18nLayout = i18n[$lang].layout.main;
</script>
{$i18nLayout[key]}
To use the lang file on a page, you need to do the following.
First, in the top-level layout:
<script>
import i18n, {useLang, setI18N} from '$lib/module/common/i18n/i18n';
const lang = useLang();
const i18nPage = writable<PathLangFile>(setI18N($lang, $page.url.pathname));
setContext('i18n', i18nPage);
$: $i18nPage = setI18N($lang, $page.url.pathname);
</script>
Then, in each page or component:
<script>
import {getI18N} from '$lib/module/common/i18n/i18n';
const i18n = getI18N();
</script>
{$i18n.key}
The value of i18n store changes based on the URL's pathname.
When using Rest parameters, you might have similar pages but with varying routes, which requires a different approach.
In each page or component, you would do the following:
<script>
const lang = getLang();
$: i18n = getI18N(key, $lang); // Here, 'key' is the key in the LangFile. While the default is the path name, in dynamic routing, it can be defined freely.
</script>
{i18n['foo']}