英文:
NextJS dynamic routes /[optional_path]/[slug].js
问题
在NextJS中,是否可以以某种方式在动态路由文件中创建可选路径?
我想要在MDX页面上使用相同的模板,根据frontmatter键“type”的值(可能等于'post'或'page'),为路由创建/blog/<slug>或/<slug>路径。如果type等于'post',则创建/blog/<slug>路径,否则直接创建/<slug>路径。
我应该如何做这个?
英文:
In NextJS, is it possible to create an optional path in the dynamic route file in some way?
I want to use the same template for mdx pages for routes /blog/<slug> or /<slug> depending upon the frontmatter key type which may equal 'post' or 'page'. If type == 'post', create a /blog/<slug> path, else just create /<slug> directly.
How do I do this?
答案1
得分: 1
您可能需要可选的匹配所有路由:
可以通过在双括号中包含参数(
[[...slug]])使捕获所有路由变为可选。例如,
pages/post/[[...slug]].js将匹配/post,/post/a,/post/a/b等等。捕获所有路由和可选捕获所有路由之间的主要区别在于,可选的情况下,也会匹配没有参数的路由(在上面的示例中为
/post)。
query对象如下:{ } // GET `/post`(空对象) { "slug": ["a"] } // `GET /post/a`(单元素数组) { "slug": ["a", "b"] } // `GET /post/a/b`(多元素数组)
英文:
You probably want optional catch all routes:
> Catch all routes can be made optional by including the parameter in double brackets ([[...slug]]).
>
> For example, pages/post/[[...slug]].js will match /post, /post/a, /post/a/b, and so on.
>
> The main difference between catch all and optional catch all routes is that with optional, the route without the parameter is also matched (/post in the example above).
>
> The query objects are as follows:
>
> json
> { } // GET `/post` (empty object)
> { "slug": ["a"] } // `GET /post/a` (single-element array)
> { "slug": ["a", "b"] } // `GET /post/a/b` (multi-element array)
>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论