如何为我的Gatsby网站创建第二个博客模板 [英] How to create a second blog template to my Gatsby Site

查看:58
本文介绍了如何为我的Gatsby网站创建第二个博客模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的盖茨比网站需要2个博客模板:

My Gatsby Site need 2 blog templates:

  1. stories-template.js
  2. products.template.js

我的故事正在运行故事模板,但是我不确定如何调整和更改gatsby-node + products.template.js中的现有代码,以为我的产品制作第二个(不同的)模板.

I have the stories-template running for my stories, but I am unsure how to tweak and change my existing codes in gatsby-node + products.template.js to make a second (different) template for my products.

我已经尝试了所有解决方案和过去的问题,但是没有运气.

I've tried all the solutions and past questions but no luck.

我在gatsby-node.js中的代码:

my code in gatsby-node.js:

const path = require('path');

exports.createPages = ({actions, graphql}) => {
const { createPage } = actions

const postTemplate = path.resolve('src/components/stories-template.js');

return graphql(`
{
    allMarkdownRemark {
        edges {
          node {
            html  
            id 
            frontmatter {
              path
              title
              author
              date
            }
          }
        }
      }
}
`).then(res => {
    if(res.errors) {
        return Promise.reject(res.errors)
    }

    res.data.allMarkdownRemark.edges.forEach(({ node }) => {
            createPage({
                path: node.frontmatter.path,
                component: postTemplate,
        })
    })
})
}

stories-template.js中的代码:

my code in stories-template.js:

import React from 'react'
import Layout from '../components/layout'


export default function Template({data}) {
const post = data.markdownRemark

return(<Layout>
    <div>
        <p>Stories</p>
        <br />
        <p>{post.frontmatter.title}</p>

        <div dangerouslySetInnerHTML={{__html: post.html}} />
    </div>
    </Layout>
)
}


export const postQuery = graphql`
query BlogPostByPath($path: String!) {
    markdownRemark(frontmatter: { path: {eq:$path}}){
        html
        frontmatter{
            path
            title
            date
            author
        }
    }
}
`

这可行,但是现在我想在products-template.js中为产品创建一个不同的模板.现在,我的产品模板基本上是从我的故事模板中复制并粘贴的.

This works but now I want to create a different template for products in a products-template.js. Right now my products-template is basically just copied and pasted from my stories-template.

我一生中似乎无法弄清这一点.

I for the life of me can't seem to figure this out.

推荐答案

就像提到的第一个评论一样,这里可能需要更多的上下文,但是我会尝试一下.我认为问题在于,无论页面如何,您都在告诉 createPage 函数使用 postTemplate 模板组件.

Like the first comment mentioned, more context might be necessary here, but I’ll give this a go. I think the problem is that regardless of the page, you’re telling the createPage function to use the postTemplate template component.

Gatsby不会自动读取模板目录或类似目录中的模板,您需要为此自己添加逻辑.

Gatsby doesn’t automatically read the templates in the template directory or anything like that, you need to add the logic for this yourself.

首先,您需要使用其他模板,例如:

First, you’ll need to require your other template, for example:

const postTemplate = path.resolve('src/components/stories-template.js');
const productsTemplate = path.resolve('src/components/products-template.js');

然后,您需要在此处决定何时使用 productsTemplate 而不是 postTemplate :

Then, you need to decide when to use productsTemplate instead of postTemplate here:

createPage({
  path: node.frontmatter.path,
  component: postTemplate,
})

例如,也许在每个Markdown文件中,您都有 template YAML前题:

For example, maybe in each Markdown file, you have template YAML frontmatter:

createPage({
  path: node.frontmatter.path,
  component: node.frontmatter.template === 'product' ? productTemplate : postTemplate,
  })

以下是我在自己的网站上尝试以更通用的方式进行处理的方法.URL结构确定模板:如果位于/journal ,则获取日记模板组件.如果位于/shop ,则获取Shop模板组件.

Here’s how I try and approach it in a slightly more generic way on my own site. The URL structure determines the template: if it’s at /journal, it gets the Journal template component. If it’s at /shop, it gets the Shop template component.

这可能不足以进入您现有的网站,但希望它可以使您更接近:

This might not be quite enough to drop into your existing site, but hopefully it gets you closer:

const path = require('path')

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  // I created an object to hold multiple templates.
  // In this case, my blog posts are at /journal and my
  // products are at /shop, so those are the keys I used here.
  // You might have a different system for determining what files
  // should use what template.
  const templates = {
    journal: path.resolve('src/templates/stories-template.js'),
    shop: path.resolve('src/templates/products-template.js'),
  }

  // Query for all Markdown "nodes"
  // Note I’m using a different GraphQL query, so you’ll need to replace this
  // with yours, or see if something with only the minimum requirements like
  // this works for you.
  return graphql(`
    {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      console.log(result.errors)
      reject(result.errors)
    }

    // Create pages from Markdown files
    result.data.allMarkdownRemark.edges.forEach(edge => {
      let slug = edge.node.fields.slug

      // Get the part of the slug we want, ex. journal
      let slugKey = slug.split('/')[1]

      // If the slug matches a template, use that, otherwise
      // fallback to the default journal template.
      // You could use your own logic here.
      let template = templates[slugKey] || templates['journal']

      createPage({
        path: slug, // required
        component: template,
        context: { slug: slug },
      })
    })
  })
}

我敢肯定,使用诺言的方式会有所改善,但是对于我来说,这很好,并且为您提供了一种添加更多模板的不错方法.

I’m sure something with how I use promises could be improved, but otherwise this is working well for me, and gives you a decent way to add in more templates.

这篇关于如何为我的Gatsby网站创建第二个博客模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆