Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sveltekit instructions #12

Merged
merged 1 commit into from
Sep 7, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,54 @@ export const i18n = createI18nStore(i18next);
</div>
```

## Usage with Sveltekit

Sveltekit shares stores across requests on server-side. This means that one users request could change the language setting of another users rendering if that is still ongoing. To avoid this issue, use `setContext` to create request-scoped store instances:

`i18n.js`:
```ts
import i18next from "i18next";
import { createI18nStore } from "svelte-i18next";

i18next.init({
lng: 'en',
resources: {
en: {
translation: {
"key": "hello world"
}
}
},
interpolation: {
escapeValue: false, // not needed for svelte as it escapes by default
}
});

export default () => createI18nStore(i18next);
```

`routes/+layout.svelte`:
```sveltehtml
<script>
import getI18nStore from "i18n.js";
import { setContext } from "svelte";

setContext('i18n', getI18nStore());
</script>
```

`routes/+page.svelte`:
```sveltehtml
<script>
import { getContext } from "svelte";

const i18n = getContext("i18n");
</script>

<div>
<h1>{ $i18n.t("key") }</h1>
</div>
```

See full example project: [Svelte example](https://github.com/NishuGoel/svelte-i18next/blob/main/example)

Loading