Gatsby極速入門—添加博客內容頁(4)

1.查數據

注意,這裏跟前面不同了,我用gatsby-node.js這個文件去提供數據,沒有什麼爲何,規定,照作就好。html

const path = require("path");
exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions

  const blogPostTemplate = path.resolve(`src/templates/blogPost.js`)

  return graphql(`
    {
      allMarkdownRemark{
        edges {
          node {
            frontmatter {
              path,
              title,
              tags
            }
          }
        }
      }
    }
  `).then(result => {
    if (result.errors) {
      return Promise.reject(result.errors)
    }
    const posts = result.data.allMarkdownRemark.edges;
    createTagPages(createPage, posts);
    posts.forEach(({ node }, index) => {
      const path = node.frontmatter.path;
      const title = node.frontmatter.title;
      createPage({
        title,
        path,
        component: blogPostTemplate,
        context: {
          pathSlug: path
        }, 
      })
    })
  })
}

很清晰明顯,這裏就說一點我傳遞了一個參數,pathSlug到內容頁。node

2.建立內容頁模板

在src>templates下建立blogPost.jsreact

import React from "react"
import { graphql,Link } from 'gatsby'
const Template = ({ data, pageContext }) => {
  const {next,prev} = pageContext;
  const {markdownRemark} = data;
  const title = markdownRemark.frontmatter.title;
  const html = markdownRemark.html;
  return (

    <div style={{
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center'
    }}>
      <h1>{title}</h1>
      <div dangerouslySetInnerHTML={{ __html: html }} />
    </div>
  )
}

export const query = graphql`
  query($pathSlug: String!) {
    markdownRemark(frontmatter: { path: { eq: $pathSlug } }) {
      html
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        path
        title
      }
    }
  }
`
export default Template;

這裏只要對應的路徑的那個文章查詢markdown

frontmatter: { path: { eq: $pathSlug } }
相關文章
相關標籤/搜索