【问题标题】:How can I get posts by year/month with nextjs and contentful?如何使用 nextjs 和 contentful 按年/月获取帖子?
【发布时间】:2021-06-05 13:28:30
【问题描述】:

我正在使用 Contentful CMS 使用 Next.js 创建博客。

我的文件夹结构现在看起来像这样pages/blog/[year]/[month]/[slug].js

年月文件夹各有自己的index.js

现在我正在处理年份部分,这就是我生成包含任何博客文章的所有年份的路径的方式。

export async function getStaticPaths() {
  let data = await client.getEntries({
    content_type: 'blog_post',
    select: 'sys.id,fields.publishDate',
    limit: 1000,
  })

  const allYears = data.items
    .map((item) => moment(item.fields.publishDate).format('YYYY'))
    .sort()

  // Get unique values.
  const years = [...new Set(allYears)]

  // Create paths.
  const paths = years.map((year) => {
    return {
      params: { year },
    }
  })

  return {
    paths,
    fallback: false,
  }
}

到目前为止一切顺利,但我不知道如何在 getStaticProps 中查询我的内容帖子?也许内容不支持它?我能做到的唯一另一种方法是手动过滤所有帖子,但这感觉不是正确的方法。

export async function getStaticProps({ params: { year } }) {
  let data = await client.getEntries({
    content_type: 'blog_post',
    // I assume I somehow have to pass my year in the query
  })

  return {
    props: {
      data,
    },
  }
}

Contentful 返回如下日期字符串:2021-03-03T00:00+01:00

所以我的问题是,我怎样才能最好地解决这个问题?有没有人遇到过同样的问题?

【问题讨论】:

  • 你想从 getStaticProps 的 Contentful 那里得到什么?给定年份的所有博客文章?
  • 是的,然后 [月] 执行相同的程序。

标签: javascript next.js contentful


【解决方案1】:

您可以使用pusblishDate 字段上的range operators 将结果过滤到给定的年份。

export async function getStaticProps({ params: { year } }) {
    const nextYear = parseInt(year, 10) + 1 // May need to parse if `year` is a string
    let data = await client.getEntries({
        content_type: 'blog_post',
        'fields.publishDate[gte]': `${year}-01-01T00:00:00Z`,
        'fields.publishDate[lt]': `${nextYear}-01-01T00:00:00Z`
    })

    return {
        props: { data }
    }
}

【讨论】:

  • 非常感谢,就是这样!我相信我会弄清楚月份部分=)。
猜你喜欢
  • 2015-04-02
  • 1970-01-01
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 1970-01-01
相关资源
最近更新 更多