NextJS 动态路由 /[可选路径]/[标识].js

huangapple go评论60阅读模式
英文:

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/&lt;slug&gt; or /&lt;slug&gt; depending upon the frontmatter key type which may equal 'post' or 'page'. If type == 'post', create a /blog/&lt;slug&gt; path, else just create /&lt;slug&gt; 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
&gt; { } // GET `/post` (empty object)
&gt; { &quot;slug&quot;: [&quot;a&quot;] } // `GET /post/a` (single-element array)
&gt; { &quot;slug&quot;: [&quot;a&quot;, &quot;b&quot;] } // `GET /post/a/b` (multi-element array)
&gt;

huangapple
  • 本文由 发表于 2023年2月19日 12:49:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定