lib icon indicating copy to clipboard operation
lib copied to clipboard

Attribute `lang` not change

Open alkorlos opened this issue 7 months ago • 4 comments

Hello, thanks for the great library

Example Locale-router-static src/hooks.server.js

// Add html `lang` attribute
return resolve({ ...event, locals: { lang: locale } }, {
  transformPageChunk: ({ html }) => html.replace(/<html.*>/, `<html lang="${locale}">`),
});

If I understand correctly, this code is supposed to change the lang attribute when switching languages, but it doesn't work, as evident in the example. <html> always have lang="en".

alkorlos avatar Jan 26 '24 11:01 alkorlos

This is doesn't look like a bug, i think its working as expected.

If I understand correctly, this code is supposed to change the lang attribute when switching languages, but it doesn't work, as evident in the example. always have lang="en".

Reason why you'd want to have a lang attribute at the first place is mainly for SEO. And when the page is loaded for the first time it has the correct lang attribute, thats what matters mostly. I have also built the example on my local and saw that generated pages have the correct lang attribute.

saya-dev avatar Feb 02 '24 01:02 saya-dev

I have also built the example on my local and saw that generated pages have the correct lang attribute.

Yes, everything is correct during the initial load, the issues arise when switching languages.

In addition to SEO, translation programs, etc., also consider the lang. If the lang correct, it will be beneficial, it definitely won't make the application work worse.

But I couldn't figure out how to implement change lang with this library.

alkorlos avatar Feb 02 '24 09:02 alkorlos

But I couldn't figure out how to implement change lang with this library.

src/routes/[lang]/+layout.svelte

Replace

<select on:change="{({ target }) => goto(target.value)}">
  {#each $locales as lc}
    <option value="/{lc}{route}" selected="{lc === $locale}">{$t(`lang.${lc}`)}</option>
  {/each}
</select>

With this

<select
  on:change={({ target }) => {
    goto(`/${target.value}${route}`);
    document.querySelector("html").setAttribute("lang", target.value);
  }}
>
  {#each $locales as lc}
    <option value={lc} selected={lc === $locale}>{$t(`lang.${lc}`)}</option>
  {/each}
</select>

saya-dev avatar Feb 02 '24 15:02 saya-dev

Thank you!

I am still working with sveltekit-i18n, and I have encountered a few issues. The code document.querySelector("html").setAttribute("lang", target.value); is not working entirely for me, so I am thinking of changing the lang attribute through src/hooks.server.js. However, for the Locale-router-static example, this works perfectly.

I will submit a pull request with this code now. If @jarda-svoboda decides that this is the best way to solve the issue, great. If not, maybe make it better.

alkorlos avatar Feb 03 '24 15:02 alkorlos