Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

Modify URL for Gatsby Contentful blog posts

I recently integrated Contentful with my Gatsby site and everything is mostly working perfectly. I am having one final issue which is around the slugs/URLs for my blog post pages.

Currently the URL for these is something like http://localhost:8000/blog/another-blog-post but I am wanting them to be http://localhost:8000/blog/year/another-blog-post with the year being created based on their published date.

In my gatsby-node.js file I have the following

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
        },
      })
    })
  }

In that example post.node.slug is 'another-blog-post' I have created the postYear variable which is correctly giving me the year they were published.
I think link to those posts with <Link className="button" aria-label={Read ${title}} to={/blog/${post.slug}} itemProp="url">

I can't figure out how to get the URL to actually include the year.

I did try changing the path, slug and to= to include ${postYear} but that leads to a 404.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I managed to solve my own question, not 100% sure if this is the best way to do it but it seems to work quite well.
I updated the path to be path: /blog/${postYear}/${post.node.slug} and then linked to it with

const postUrl = `/blog/${post.postYear}/${post.slug}`
<Link className="button" aria-label={`Read ${title}`} to={postUrl} itemProp="url">

Tested with a variety of years and seems to be doing what I would expect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...