Create a Fast Site with GatsbyJS

Create Page from Data

Gatsby APIs

Gatsby exposes some APIs for you to hook into different lifecycles:

Create Pages from Data

Add Path for Each Markdown Page

blogs/my-first-blog.md
md
---
title: 'My First Blog'
date: '2019-07-06'
path: '/my-first-blog'
---
I'm so happy to write my first blog in Gatsby!
blogs/second-blog.md
md
---
title: 'My Second Blog'
date: '2019-07-07'
path: '/second-blog'
---
This is my second blog.
Cool right?

Create Template for BlogPost

bash
mkdir src/templates
touch src/templates/blog-template.jsx
src/templates/blog-template.jsx
jsx
import React from 'react';
import { Layout } from '../components/layout';
const BlogTemplate = () => {
return (
<Layout>
<article>
<h1>Hello Blog Post!</h1>
</article>
</Layout>
);
};
export default BlogTemplate;

Create Page with Gatsby createPages API

bash
touch gatsby-node.js
gatsby-node.js
js
const path = require('path');
const blogTemplate = path.resolve(
__dirname,
'src',
'templates',
'blog-template.jsx'
);
exports.createPages = async ({ actions, graphql }) => {
const { createPage } = actions;
const result = await graphql(`
{
allMarkdownRemark {
edges {
node {
frontmatter {
path
}
}
}
}
}
`);
result.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.frontmatter.path,
component: blogTemplate,
});
});
};

Inject Data in Template

src/templates/blog-template.jsx
jsx
import { graphql } from 'gatsby';
import React from 'react';
import { Layout } from '../components/layout';
const BlogTemplate = ({ data }) => {
const post = data.markdownRemark;
return (
<Layout>
<article>
<h1>{post.frontmatter.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
</article>
</Layout>
);
};
export default BlogTemplate;
export const pageQuery = graphql`
query BlogPostById($id: String!) {
markdownRemark(id: { eq: $id }) {
html
frontmatter {
title
}
}
}
`;
gatsby-node.js
js
...
exports.createPages = async ({ actions, graphql }) => {
const { createPage } = actions;
const result = await graphql(`
{
allMarkdownRemark {
edges {
node {
id
frontmatter {
path
}
}
}
}
}
`);
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.frontmatter.path,
component: blogTemplate,
context: {
id: node.id
}
});
});
};
Comments

There is no comment on this post yet.

Issue on this page? Report here