Skip to content

Commit bf7fbbd

Browse files
committed
feat: added support for gatsby path placeholderss(e.g. :id)
1 parent f57f9e2 commit bf7fbbd

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

src/gatsby-node.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ exports.onCreatePage = async ({ page, actions }, pluginOptions) => {
7474
const newPath = routed ? `/${language}${page.path}` : page.path
7575
return {
7676
...page,
77+
matchPath:
78+
!page.matchPath && !routed && page.path.indexOf(":") >= 0
79+
? page.path
80+
: page.matchPath,
7781
path: newPath,
7882
context: {
7983
...page.context,

src/wrap-page.js

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,25 @@
11
import React from "react"
22
import browserLang from "browser-lang"
3-
import { withPrefix } from "gatsby"
3+
import { navigate } from "gatsby"
44
import { IntlProvider } from "react-intl"
55
import { IntlContextProvider } from "./intl-context"
66

77
const preferDefault = m => (m && m.default) || m
88

9+
const replaceParams = (path, props) => {
10+
const regex = /\:(\w+)/g
11+
12+
let newPath = path
13+
let match
14+
while ((match = regex.exec(path)) !== null) {
15+
newPath = newPath.replace(
16+
new RegExp(match[0], "g"),
17+
props[match[1]] || match[0]
18+
)
19+
}
20+
return newPath
21+
}
22+
923
const polyfillIntl = language => {
1024
const locale = language.split("-")[0]
1125
try {
@@ -23,7 +37,7 @@ const polyfillIntl = language => {
2337
}
2438
}
2539

26-
const withIntlProvider = (intl) => children => {
40+
const withIntlProvider = intl => children => {
2741
polyfillIntl(intl.language)
2842
return (
2943
<IntlProvider
@@ -69,9 +83,13 @@ export default ({ element, props }, pluginOptions) => {
6983
}
7084

7185
const queryParams = search || ""
72-
const newUrl = withPrefix(`/${detected}${originalPath}${queryParams}`)
86+
const pathWithParams = replaceParams(originalPath, props)
87+
88+
const newUrl = `/${detected}${pathWithParams}${queryParams}`
7389
window.localStorage.setItem("gatsby-intl-language", detected)
74-
window.location.replace(newUrl)
90+
navigate(newUrl, {
91+
replace: true,
92+
})
7593
}
7694
}
7795
const renderElement = isRedirect

0 commit comments

Comments
 (0)