如何解决修改 Gatsby Contentful 博客文章的 URL
我最近将 Contentful 与我的 Gatsby 网站集成,一切都运行良好。 我遇到了最后一个问题,与我的博客文章页面的 slugs/URL 相关。
目前这些 URL 类似于 http://localhost:8000/blog/another-blog-post 但我希望它们是 http://localhost:8000/blog/year/another-blog-post根据发布日期创建年份。
在我的 gatsby-node.js 文件中,我有以下内容
if (posts.length > 0) {
posts.forEach((post,index) => {
const previousPostId = post.previous?.id
const nextPostId = post.next?.id
const postYear = new Date(post.node.publishDate).getFullYear();
createPage({
path: `/blog/${post.node.slug}`,component: blogPost,context: {
id: post.id,previousPostId,nextPostId,slug: post.node.slug
},})
})
}
在那个例子中,post.node.slug
是“another-blog-post”
我创建了 postYear
变量,它正确地给了我它们的出版年份。
我认为这些帖子的链接是 <Link className="button" aria-label={
Read ${title}} to={
/blog/${post.slug}} itemProp="url">
我不知道如何让 URL 实际包含年份。
我确实尝试将 path
、slug
和 to=
更改为包含 ${postYear}
,但这会导致 404。
解决方法
我设法解决了我自己的问题,不是 100% 确定这是否是最好的方法,但它似乎工作得很好。
我将路径更新为 path: /blog/${postYear}/${post.node.slug}
,然后使用
const postUrl = `/blog/${post.postYear}/${post.slug}`
<Link className="button" aria-label={`Read ${title}`} to={postUrl} itemProp="url">
经过多年的测试,似乎达到了我的预期。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。