如何创建单个 Gatsby 页面以按 tag/category 显示和过滤所有博客文章

How to create a single Gatsby Page to show and filter all blog posts by tag/category

您好,我正在使用 Gatsby 和 Netlify CMS 构建博客。我从 gatsby-starter-netlify-cms 模板开始。

我有 /blog 页面,我目前在其中显示所有帖子以及所有标签的列表。 当用户点击一个标签时,它当前被重定向到 tags/name-of-tag 页面,其中显示所有标记为该标签的帖子的列表。

我想要的是直接过滤/blog页面上的列表。 这样我就只有一个页面可以按标签(也可能按术语搜索)显示和过滤博客文章。

所以标签链接应该重定向到 /blog?tag-name 或类似的东西。 我不确定如何告诉 Gatsby 创建一个可以注入 filter 值以便将其传递给页面查询的页面..

目前 /tags/ 页面是这样创建的:

// Tag pages:
    let tags = []
    // Iterate through each post, putting all found tags into `tags`
    posts.forEach((edge) => {
      if (_.get(edge, `node.frontmatter.tags`)) {
        tags = tags.concat(edge.node.frontmatter.tags)
      }
    })
    // Eliminate duplicate tags
    tags = _.uniq(tags)

    // Make tag pages
    tags.forEach((tag) => {
      const tagPath = `/tags/${_.kebabCase(tag)}/`

      createPage({
        path: tagPath,
        component: path.resolve(`src/templates/tags.js`),
        context: {
          tag,
        },
      })
    })

这是我的博客页面查询(我希望能够按标签过滤的那个):

export const blogPageQuery = graphql`
  query BlogPageTemplate {
    markdownRemark(frontmatter: { templateKey: { eq: "blog-page" } }) {
      frontmatter {
        image {
          childImageSharp {
            fluid(maxWidth: 2048, quality: 80) {
              ...GatsbyImageSharpFluid
            }
          }
        }
        heading
        subheading
      }
    }
    allMarkdownRemark(
      sort: { order: DESC, fields: [frontmatter___date] }
      filter: { frontmatter: { templateKey: { eq: "blog-post" } } }
    ) {
      edges {
        node {
          id
          fields {
            slug
          }
          excerpt(pruneLength: 180)
          frontmatter {
            date(formatString: "MMMM DD, YYYY")
            title
            description
            featuredpost
            featuredimage {
              childImageSharp {
                fluid(quality: 50, maxWidth: 512) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        }
      }
    }
  }
`

I'm not sure how to tell Gatsby to create a single page with possibility to inject a filter value in order to pass it to the page query.

你不能。在页面查询中过滤数据的唯一方法是使用上下文传递数据。就像您在标签页面中所做的那样:

  createPage({
    path: tagPath,
    component: path.resolve(`src/templates/tags.js`),
    context: {
      tag,
    },
  })

最简单和原生的方法是使用 /tag/tag-name 页面,它旨在按标签名称进行过滤,否则,您将需要获取 URL 参数并在 JavaScript filter函数过滤所有来自页面查询的数据。由于您缺少博客页面的呈现部分...类似这种方法的方法应该有效:

const BlogTemplate=({ data }){
    if(typeof window !== "undefined"){
      const queryString = window.location.search;
      const urlParams = new URLSearchParams(queryString);
      const urlTag= urlParams.get('tag');
      const filteredPosts= data.allMarkdownRemark.edges.node.filter(node=> node.frontmatter.tag.includes(urlTag))
      const loopData= urlParams.has('tag') ? filteredPosts : data
   }
   
return loopData.allMarkdownRemark.edges.node.map(node=> <h1 key={node.title}>{node.title}</h1>)

}

注意:当然,根据您的需要进行调整,但请理解。

另请注意,您需要将所有 window 逻辑包装在 typeof window !== "undefined" 条件中,因为 in the SSR window (and other global objects) are not available.

关键部分是使用 data 还是你的 filteredPosts 取决于 URL 参数的存在,所以如果它存在,你将需要过滤数据否则,您需要使用“默认”data(未过滤)。

很难猜测代码的行为方式,但这个想法依赖于根据 URL 更改可迭代数据,如果需要,请使用一些挂钩。

根据您的查询,您的博客似乎在博客模板查询中不包含任何 tag 字段,因此您需要添加它以允许 filter 循环工作。

代码运行后,您将需要添加适当的控件以避免在某些字段丢失时出现代码中断,但思路和路径是这样的。