Create Page from Data
Gatsby APIs
Gatsby exposes some APIs for you to hook into different lifecycles:
- Gatsby Node APIs: accessed with
gatsby-node.js
file. - Gatsby Browser APIs: accessed with
gatsby-browser.js
file - Gatsby SSR APIs: accessed with
gatsby-ssr.js
file
Create Pages from Data
Add Path for Each Markdown Page
blogs/my-first-blog.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
---
title: 'My Second Blog'
date: '2019-07-07'
path: '/second-blog'
---
This is my second blog.
Cool right?
Create Template for BlogPost
mkdir src/templates
touch src/templates/blog-template.jsx
src/templates/blog-template.jsx
import * as 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
touch gatsby-node.js
gatsby-node.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
import { graphql } from 'gatsby';
import * as 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
...
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
}
});
});
};