#Language Toggle
7 messages · Page 1 of 1 (latest)
Hi @compact vine. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, it is possible to create a component that allows users to switch between languages in Astro. Here's a step-by-step guide on how to do it:
- Create a component to show a link for each language. This component will be named
LanguagePicker.astroand will be located in thesrc/components/directory. The code for this component is as follows:
---import { languages } from '../i18n/ui';---
<ul>
{Object.entries(languages).map(([lang, label]) => (
<li>
<a href={`/${lang}/`}>{label}</a>
</li>
))}
</ul>
- Add
<LanguagePicker />to your site so it is shown on every page. The example below adds it to the site footer in a base layout. This layout will be namedBase.astroand will be located in thesrc/layouts/directory. The code for this layout is as follows:
---import LanguagePicker from '../components/LanguagePicker.astro';
import { getLangFromUrl } from '../i18n/utils';
const lang = getLangFromUrl(Astro.url);---
<html lang={lang}>
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<title>Astro</title>
</head>
<body>
<slot />
<footer>
<LanguagePicker />
</footer>
</body>
</html>
This will create a list of links, each one corresponding to a different language. When a user clicks on a link, they will be redirected to the version of the site in the corresponding language.
For more information, you can refer to the Astro documentation on i18n (https://docs.astro.build/en/recipes/i18n#let-users-switch-between-languages).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@compact vine kapa.ai is still learning and improving, please let us know how it did by reacting below
@lime dome Will the page refresh?
Let me check the knowledge base for you. One moment! :books:
Yes, the page will refresh when a user clicks on a language link. This is because Astro uses standard HTML <a> elements to navigate between pages (also called routes), with traditional page refreshes. This is mentioned in the Astro tutorial on creating your first Astro page (https://docs.astro.build/en/tutorial/2-pages/1#add-navigation-links).
However, if you want to avoid a full page refresh when switching languages, you can use the data-astro-reload attribute. This attribute was mentioned in a Github issue comment (https://github.com/withastro/astro/issues/9359) where a user added data-astro-reload to a language switching button, causing the page to refresh and solve an issue with a chat widget needing to refresh when a user switched languages. The code for this would look like:
<a data-astro-reload href="/en/">English</a>
<a data-astro-reload href="/fr/">French</a>