---
# System prepended metadata

title: 設置語言轉換器
tags: [Next.Js 14 with APP Router]

---

設置語言轉換器
===

###### With Next.js App Router + next-intl
:::info
:radio_button: [回到目錄攻略](https://hackmd.io/@hJJ8etrATgudRfKA1gryew/BJiplPwMC)
:::

1.加入component與style
---
除了加入語言轉換器的元件，當然也要有與它相關的風格設計，相關位置如下：
```
└── src
    └── app
        └── [locale]
            ├── [...rest]
            ├── components (+)
            │    └── LocalSwitcher.tsx (+)
            ├── style (+)
            │    └── f2e-localswitcher.css (+)
            ├── layout.tsx
            └── main
```

2.寫入檔案
---
> @locale/style/f2e-localswitcher.css
```css=
.f2e-localswitcher {
  position: absolute;
  right: 20px;
}
```

> @locale/components/LocalSwitcher.tsx
```typescript=
"use client"; //因為需要路徑pathname，走的是client端
import "@locale/style/f2e-localswitcher.css";
import Link from "next/link";
import { usePathname } from "next/navigation";

const languages = [
  { key: "en", label: "English" },
  { key: "zh", label: "繁體中文" },
];

export default function LocaleSwitcher() {
  const pathName = usePathname();

  // *網址根據選擇的語言做變化
  const redirectedPathName = (locale: string) => {
    if (!pathName) return "/";
    const segments = pathName.split("/");
    segments[1] = locale;
    return segments.join("/");
  };

  return (
    <ul className="f2e-localswitcher">
      {languages.map(({ key, label }) => (
        <li key={key}>
          <Link locale={key} href={redirectedPathName(key)}>
            {label}
          </Link>
        </li>
      ))}
    </ul>
  );
}
```

<font color="#F7A004">* 解釋一下這個Funciton：`redirectedPathName`</font>
- `redirectedPathName`是用來根據給定的語言(locale)產生重定向後的路徑名。
- 它首先檢查當前頁面的路徑名，然後將其分割成路徑段(segments)。
- 再將第二個路徑段（通常是語言代碼）替換為指定的語言(locale)。
- 最後將路徑段重新組合成一個新的字符串。

3.layout調整
---
> @locale/layout.tsx

因為語言轉換器是要貫穿整個網站，所以也必須加進`layout.tsx`中。以下有註解(+)表示新加入：
```typescript=
import { locales } from "@lib/config";
import LocaleSwitcher from "@locale/components/LocalSwitcher"; // (+)
import type { Metadata } from "next";
import { NextIntlClientProvider, useMessages } from "next-intl";
import { unstable_setRequestLocale } from "next-intl/server";
import { Inter } from "next/font/google";

...

type Props = { children: React.ReactNode; params: { locale: string } };

const RootLayout = ({ children, params: { locale } }: Props) => {
  const messages = useMessages();
  unstable_setRequestLocale(locale);
  return (
    <html lang={locale}>
      <body className={inter.className}>
        <LocaleSwitcher /> // (+)
        <NextIntlClientProvider messages={messages}>
          {children}
        </NextIntlClientProvider>
      </body>
    </html>
  );
};

export default RootLayout;
```


 4.結果呈現
 ---
 先暫時用比較陽春的風格來表現昂！
 可以看到網址與也跟著語言轉換器一同變化囉～
 
 ![20240508_103743](https://hackmd.io/_uploads/ryT3rDOfR.gif)
