Create a gist now

Instantly share code, notes, and snippets.

@Zackio /about.md Secret
Last active Jun 25, 2018

Embed
What would you like to do?
Example of how to set a separate template for markdown post and pages in Gatsby.
title layout
About
page
const _ = require('lodash')
const Promise = require('bluebird')
const path = require('path')
const { createFilePath } = require('gatsby-source-filesystem')
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
const postTemplate = path.resolve('./src/templates/blog-post.js')
const pageTemplate = path.resolve('./src/templates/page.js')
resolve(
graphql(
`
{
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }, limit: 1000) {
edges {
node {
fields {
slug
}
frontmatter {
title
layout
subtitle
category
}
}
}
}
}
`
).then(result => {
if (result.errors) {
console.log(result.errors)
reject(result.errors)
}
// Create blog posts pages.
const posts = result.data.allMarkdownRemark.edges;
_.each(posts, (post, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1].node;
const next = index === 0 ? null : posts[index - 1].node;
let template = postTemplate;
if( post.node.frontmatter.layout === 'page') {
template = pageTemplate;
}
createPage({
path: post.node.fields.slug,
component: template,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
})
})
)
})
}
exports.onCreateNode = ({ node, boundActionCreators, getNode }) => {
const { createNodeField } = boundActionCreators
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: `slug`,
node,
value,
})
}
}
import React from 'react'
import Link from 'gatsby-link'
import get from 'lodash/get'
import Helmet from 'react-helmet'
import Bio from '../components/Bio'
import { rhythm } from '../utils/typography'
class BlogIndex extends React.Component {
render() {
const siteTitle = get(this, 'props.data.site.siteMetadata.title')
const posts = get(this, 'props.data.allMarkdownRemark.edges')
return (
<div>
<Helmet title={siteTitle} />
<Bio />
{posts.map(({ node }) => {
const title = get(node, 'frontmatter.title') || node.fields.slug
return (
<div key={node.fields.slug}>
<h3
style={{
marginBottom: rhythm(1 / 4),
}}
>
<Link style={{ boxShadow: 'none' }} to={node.fields.slug}>
{title}
</Link>
</h3>
<small>{node.frontmatter.date}</small>
<p dangerouslySetInnerHTML={{ __html: node.excerpt }} />
</div>
)
})}
</div>
)
}
}
export default BlogIndex
export const pageQuery = graphql`
query IndexQuery {
site {
siteMetadata {
title
}
}
allMarkdownRemark(
sort: { fields: [frontmatter___date], order: DESC }
filter: {
id: { regex: "/posts/" }
}
) {
edges {
node {
excerpt
fields {
slug
}
frontmatter {
date(formatString: "DD MMMM, YYYY")
title
}
}
}
}
}
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment