Skip to content

Commit 2a58b36

Browse files
committed
add translateUrl example in urls guide
1 parent a9e428d commit 2a58b36

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/content/docs/guides/urls.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,41 @@ export const reroute = ({url}) => {
196196
```
197197
198198
The implementation of `deLocalize` is left as an exercise.
199+
200+
## Path translation
201+
202+
Most of the time, when the locale in a page is changed (using a drop-down for
203+
example), it is desired to go to the corresponding page in the new locale
204+
instead of jumping to the home page. To achieve this, the current path must be
205+
translated to the new locale. The steps are as follow:
206+
207+
1. DeLocalize the path to remove any prefixes
208+
1. Extract the dynamic params for that path and get the alternate patterns
209+
1. Fill the params on the pattern of the desired new locale
210+
1. Localize the new path with the new locale
211+
212+
wuchale provides the utilities to do these easily. For example, with the default localization:
213+
214+
```ts
215+
// src/lib/utils.js
216+
217+
import {deLocalizeDefault, fillParams, localizeDefault} from "wuchale/url"
218+
import {matchUrl} from "../locales/main.url.js"
219+
220+
/**
221+
* @param {string} url
222+
* @param {import("../locales/data.js").Locale} locale
223+
*/
224+
function translateUrl(url, locale) {
225+
const [pathOnly, prevLocale] = deLocalizeDefault(url, locales);
226+
const result = matchUrl(pathOnly, prevLocale)
227+
if (result.path !== null) {
228+
const targetPath = fillParams(result.params, result.altPatterns[locale])
229+
return localizeDefault(targetPath, locale)
230+
}
231+
return localizeDefault(url, locale)
232+
}
233+
```
234+
235+
If you use other ways of localization/de-localization, you can adapt it by
236+
changing the corresponding functions.

0 commit comments

Comments
 (0)