如何解决如何使用nextjs和contentful按年/月获得帖子?
我正在使用 Contentful CMS 使用 Next.js 创建一个博客。
我的文件夹结构现在看起来像这样 pages/blog/[year]/[month]/[slug].js
年和月文件夹都有自己的 index.js
现在我正在研究年份部分,这就是我生成包含任何博客文章的所有年份的路径的方式。
import
到目前为止一切顺利,但我不知道如何在 getStaticProps 中查询我的内容丰富的帖子?也许 contentful 不支持它?我能够做到的唯一另一种方法是手动过滤所有帖子,但感觉这不是正确的方法。
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,}
}
Contentful 返回这样的日期字符串:2021-03-03T00:00+01:00
所以我的问题是,我怎样才能最好地解决这个问题?有没有人遇到过同样的问题?
解决方法
您可以使用 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 }
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。