【问题标题】:Modify URL for Gatsby Contentful blog posts修改 Gatsby Contentful 博客文章的 URL
【发布时间】:2021-04-17 19:33:28
【问题描述】:

我最近将 Contentful 与我的 Gatsby 网站集成在一起,并且大部分都运行良好。 最后一个问题是关于我的博客文章页面的 slugs/URLs。

目前这些 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 实际包含年份。

我确实尝试将 pathslugto= 更改为包含 ${postYear},但这会导致 404。

【问题讨论】:

    标签: gatsby contentful


    【解决方案1】:

    我设法解决了我自己的问题,不是 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">
    

    经过多年的测试,似乎符合我的预期。

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 2019-01-13
      • 2021-04-12
      • 1970-01-01
      • 2023-03-18
      • 2018-10-26
      • 2018-05-16
      • 1970-01-01
      • 2017-09-26
      相关资源
      最近更新 更多