diff --git a/src/gatsby-node.js b/src/gatsby-node.js index 4f7af36..484b606 100644 --- a/src/gatsby-node.js +++ b/src/gatsby-node.js @@ -74,6 +74,10 @@ exports.onCreatePage = async ({ page, actions }, pluginOptions) => { const newPath = routed ? `/${language}${page.path}` : page.path return { ...page, + matchPath: + !page.matchPath && !routed && page.path.indexOf(":") >= 0 + ? page.path + : page.matchPath, path: newPath, context: { ...page.context, diff --git a/src/wrap-page.js b/src/wrap-page.js index b32bb84..4217e0f 100644 --- a/src/wrap-page.js +++ b/src/wrap-page.js @@ -1,11 +1,25 @@ import React from "react" import browserLang from "browser-lang" -import { withPrefix } from "gatsby" +import { navigate } from "gatsby" import { IntlProvider } from "react-intl" import { IntlContextProvider } from "./intl-context" const preferDefault = m => (m && m.default) || m +const replaceParams = (path, props) => { + const regex = /\:(\w+)/g + + let newPath = path + let match + while ((match = regex.exec(path)) !== null) { + newPath = newPath.replace( + new RegExp(match[0], "g"), + props[match[1]] || match[0] + ) + } + return newPath +} + const polyfillIntl = language => { const locale = language.split("-")[0] try { @@ -23,7 +37,7 @@ const polyfillIntl = language => { } } -const withIntlProvider = (intl) => children => { +const withIntlProvider = intl => children => { polyfillIntl(intl.language) return ( { } const queryParams = search || "" - const newUrl = withPrefix(`/${detected}${originalPath}${queryParams}`) + const pathWithParams = replaceParams(originalPath, props) + + const newUrl = `/${detected}${pathWithParams}${queryParams}` window.localStorage.setItem("gatsby-intl-language", detected) - window.location.replace(newUrl) + navigate(newUrl, { + replace: true, + }) } } const renderElement = isRedirect