【问题标题】:How can I display blog posts from Contentful's API using multiple templates when programmatically creating posts in Gatsby在 Gatsby 中以编程方式创建帖子时,如何使用多个模板显示来自 Contentful API 的博客帖子
【发布时间】:2021-10-28 17:14:33
【问题描述】:

我一直在关注beginner tutorial on Gatsby's website,并且对使用多个博客帖子模板有疑问。

如果博客需要使用两个或多个模板,例如:

  1. 一个模板,一个图像和一个富文本块。
  2. 一个包含多张图片和多块富文本的模板。

如何在 Gatsby 中以编程方式在同一个 URL 结构中生成页面时实现这一点,例如:

/blog/post-title-1(使用模板 1) /blog/post-title-2(使用模板 2)

谢谢。

【问题讨论】:

    标签: gatsby contentful


    【解决方案1】:

    当然,这是可行的,但请记住,您需要向代码提供该信息(选择的布局)。如果您使用文件系统路由 API 遵循本教程,则需要使用 gatsby-node.js 切换到创建动态页面的“经典”版本,因为需要在某处提供这种逻辑以让 Gatsby 意识到那个。

    您可以添加一个名为 layout 的 Contentful 字段,在这种情况下可以是整数或类似的东西,然后在您的 gatsby-node.js 中:

    const path = require("path")
    
    exports.createPages = async ({ graphql, actions, reporter }) => {
      const { createPage } = actions
    
      const result = await graphql(
        `
              {
                allContentfulBlogPost {
                  edges {
                    node {
                      layout
                      slug
                    }
                  }
                }
              }
        `
      )
    
      if (result.errors) {
        reporter.panicOnBuild(`Error while running GraphQL query.`)
        return
      }
    
    
      const blogPostTemplate1 = path.resolve(`src/templates/blog-post-1.js`)
      const blogPostTemplate2 = path.resolve(`src/templates/blog-post-2.js`)
    
      const posts = result.data.allContentfulBlogPost.edges
      posts.forEach((post, index) => {
        createPage({
          path: `/blog/${post.node.slug}/`,
          component: post.node.layout === "1" ? blogPostTemplate1 : blogPostTemplate2,
          context: {
            slug: post.node.slug
          },
        })
       })
      })
    }
    

    文件系统路由 API 使您免于在 gatsby-node.js 中为标准方法添加这种查询 + 逻辑,但由于它不支持过滤(尚)您需要添加一些您需要的逻辑回到“标准”方法。

    基本上,您正在获取 Contentful 数据,查询 sluglayout(新字段),并根据该条件创建动态页面。

    请注意,在component 中,您是根据使用三元条件的布局字段选择一个或另一个模板。当然,根据需要调整它。理想情况下,在复杂的方法(超过 2 个布局)中,它应该是一个可读性的函数。

    您的遗留代码的其余部分(您的模板查询)将单独工作,因为您使用以下上下文提供 slug(就像您之前所做的那样):

          context: {
            slug: post.node.slug
          },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多