-
The accessibility section of the docs recommends using server hooks with Something like |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I put together this demo that makes use of form actions to change the page's language: https://www.sveltelab.dev/xya98neroqbjl4t As long as you have server side rendering, this solutions works with and without JS. Exampleapp.html <html lang="%lang%"> +page.svelte <form method="POST" use:enhance>
<button formaction="?l=en">English</button>
<button formaction="?l=zh">中文</button>
</form> +page.server.js import { redirect } from '@sveltejs/kit'
export const load = async ({ cookies, depends }) => {
depends('site:lang')
const lang = cookies.get('lang')
console.log('loading lang', {lang})
let title = 'Language switcher!'
if (lang === 'zh') {
title = '语言切换器'
}
return {title};
};
const allowedLanguages = ['en', 'zh']
/** @type {import('./$types').Actions} */
export const actions = {
default: async ({ url, cookies }) => {
const lang = url.searchParams.get('l')
console.log({lang})
if (allowedLanguages.includes(lang)) {
cookies.set('lang', lang, { path: '/' })
}
// redirect is necessary for full page load
throw redirect(303, '/')
}
}; hooks.server.js /** @type {import('./$types').Handle */
export async function handle({ event, resolve }) {
const lang = event.cookies.get('lang') || 'en'
console.log('hook lang is', lang)
const response = await resolve(event, {
transformPageChunk: ({html}) => html.replace('%lang%', lang)
});
return response;
} For a pure client-side solution, you can set the document language only using JS with: document.documentElement.lang = 'language-code' |
Beta Was this translation helpful? Give feedback.
I put together this demo that makes use of form actions to change the page's language: https://www.sveltelab.dev/xya98neroqbjl4t
As long as you have server side rendering, this solutions works with and without JS.
Example
app.html
+page.svelte
+page.server.js