Home > front end >  How to set <html lang> dynamically for different pages in SvelteKit?
How to set <html lang> dynamically for different pages in SvelteKit?

Time:01-10

In my SvelteKit app, some pages are in English (en) and some pages are in Farsi (fa). The app.html file sets the lang attribute to en statically for the entire app. How can I make the lang attribute dynamic and set it to a different value for different pages depending on the language of the page?"

I tried to bind the lang attribute to a dynamic value using lang={lang} in the app.html file, but this did not work because variables cannot be used in the app.html file in the same way they can be used in .svelte files.

CodePudding user response:

You can make the lang attribute dynamic as outlined in The "lang" attribute part of the documentation with the help of the handle hook:

<!-- src/app.html -->
<html lang="%lang%">
// src/hooks.server.js
export function handle({ event, resolve }) {
  return resolve(event, {
    transformPageChunk: ({ html }) => html.replace('%lang%', get_lang(event))
  });
}

CodePudding user response:

Server hooks are what you're looking for, you can check whether or not you're on an English or Farsi page from the hook event object. Assuming you're using TypeScript this is approximately what the src/hooks.server.ts file will look like.

export const handle = (async ({ event, resolve }) => {
  let lang = event.url.startsWith('/fa') ? 'fa' : 'en';
  return resolve(event, {
    transformPageChunk: ({ html }) => html.replace('%lang%', lang)
  });
}) satisfies Handle;

This is the recommended way of injecting values in the HTML that's usually inaccessible to Svelte. There's actually a closed issue about this on the official SvelteKit repo.

  • Related