sveltejs / sapper

The next small thing in web development, powered by Svelte
https://sapper.svelte.dev
MIT License
7k stars 434 forks source link

Support for dynamically setting the `lang` attribute #1695

Closed ehrencrona closed 3 years ago

ehrencrona commented 3 years ago

Currently the lang attribute in the html tag is hard-coded in template.html. This makes it impossible to build multi-language sites with Sapper.

This PR allows routes to export a lang function in addition to preload. It gets the same path information as preload and returns a language code to use for the page. The most specific component wins.

See discussion in #576

I know Sapper is currently in maintenance mode and that this is tied up in the much larger internationalization question, but this feels like a fairly straightforward extension. At Hyperlab we are currently building two multi-language sites. Without the ability to determine the language dynamically we would need to fork Sapper.

Before submitting the PR, please make sure you do the following

Tests

benmccann commented 3 years ago

There are three PRs open for dynamically updating the template (most recently https://github.com/sveltejs/sapper/pull/1642). I wonder if coming up with a good solution there might be a more generic solution to a wider class of issues

benmccann commented 3 years ago

Actually, do we even need to do anything or is this already supported?

<svelte:head>
    <html lang="sw" />
</svelte:head>
ehrencrona commented 3 years ago

@benmccann That will create an html tag inside head, but it's the very top-level html tag we want to modify. If it wasn't, it would indeed be easier.

benmccann commented 3 years ago

Ah, you're right. I saw someone posted that as an example, so assumed it worked 😛 How about doing something like this?

onMount(() => {
  document.documentElement.lang = 'sw';
});
ehrencrona commented 3 years ago

How about doing something like this?

onMount(() => {
  document.documentElement.lang = 'sw';
});

That will work on the client side, but for the benefit of Google indexing in the correct language we need to be able to serve the correct language from the server side.

I guess it would be another road towards implementing support, though, to offer a document object on the server side, which per se might not be unreasonable.

benmccann commented 3 years ago

Thanks for this PR!! I don't think we'll be adding anything new to Sapper at this point, but this now exists in SvelteKit! https://github.com/sveltejs/kit/pull/670