前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Gatsby入门指南—添加博客内容页(4)

Gatsby入门指南—添加博客内容页(4)

作者头像
前端大彬哥
发布2019-05-29 16:00:40
3940
发布2019-05-29 16:00:40
举报
文章被收录于专栏:大前端666大前端666

1.查数据

注意,这里跟前面不一样了,我用gatsby-node.js这个文件去提供数据,没有什么为什么,规定,照做就好。

代码语言:javascript
复制
    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到内容页。

2.创建内容页模板

在src>templates下创建blogPost.js

代码语言:javascript
复制
    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;

这里只要对应的路径的那个文章查询

代码语言:javascript
复制
    frontmatter: { path: { eq: $pathSlug } }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.05.26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.查数据
  • 2.创建内容页模板
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档