【问题标题】:Create pages in gatsby using different templates在 gatsby 中使用不同的模板创建页面
【发布时间】:2020-01-30 22:51:26
【问题描述】:

我是 gatsby 的新手,并尝试使用不同的模板以编程方式创建页面,但我正在为此苦苦挣扎。

这是我的 gatsby 节点文件,它可以很好地创建团队成员页面,但是当我想使用位于同一文件夹 /templates 的新模板创建博客文章时出现问题

const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const result = await graphql(`
    query {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `)

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/templates/member-info.js`),
      context: {
        slug: node.fields.slug,
      },
    })
  })
}

我尝试了不同的方法,但无法找到解决方案。 谢谢!

【问题讨论】:

    标签: javascript graphql gatsby


    【解决方案1】:

    最天真的方法是使用不同的模板组件调用createPage。更健壮的方法可能是在 frontmatter 中定义模板名称并使用它来动态构造各个组件的路径,如下所示:

    // some markdown file
    ---
    template: member-info
    ---
    
    // gatsby-node.js
    exports.createPages = async ({ graphql, actions }) => {
      const { createPage } = actions
      const result = await graphql(`
        query {
          allMarkdownRemark {
            edges {
              node {
                frontmatter {
                  template
                }
                fields {
                  slug
                }
              }
            }
          }
        }
      `)
    
      result.data.allMarkdownRemark.edges.forEach(({ node }) => {
        createPage({
          path: node.fields.slug,
          component: path.resolve(`./src/templates/${template}.js`),
          context: {
            slug: node.fields.slug,
          },
        })
      })
    }
    

    【讨论】:

    • 谢谢@PavelYe!我会尽快尝试一下
    • 不客气。如果您认为其中有价值,请随时投票/接受我的回答。谢谢
    • 我收到以下错误:Cannot query field "template" on type "MarkdownRemarkFrontmatter" 我知道我应该在 frontmatter 中定义 template 名称,但不知道该怎么做
    • 是的,你的想法是正确的。我会更新我的答案。如果你不熟悉 frontmatter => gatsbyjs.org/docs/adding-markdown-pages/…
    猜你喜欢
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2021-04-01
    • 2016-07-31
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    相关资源
    最近更新 更多