javascript - 使用不同的模板在 gatsby 中创建页面

标签 javascript graphql gatsby

我是 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,
      },
    })
  })
}

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

最佳答案

最简单的方法是使用不同的模板组件调用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,
      },
    })
  })
}

关于javascript - 使用不同的模板在 gatsby 中创建页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59270438/

相关文章:

javascript - 与 Background 的交互被 Div 在后台阻止

javascript - jQuery,必要时更新内容

javascript - 向折线图添加工具提示未显示

javascript - 使用Apollo+Vue : What parameters are given to the "update" callback?

node.js - Gatsby - 无法解析 'path' 中的 'C:\Users\...\gatsby-starter-hello-world\node_modules\postcss\lib'

javascript - 无法更新 Apexcharts 组件值

javascript - Apollo 客户端 : keeping data from previous query while waiting for next fetching

javascript - 不使用 refetchQueries 更新 Apollo GraphQL 缓存?

javascript - 该插件文件同时使用 CommonJS 和 ES6 模块系统,我们不支持

reactjs - GatsbyJS Build – 窗口未定义/模块未定义