如何将Contentful CMS与Gatsby页面对接以搭建博客?
Complete Contentful-Gatsby Blog Integration Fix
Got it, let's wrap up this Contentful-Gatsby blog setup. Your existing code has the foundation—you just need to add the logic to iterate over your Contentful blog entries and generate individual pages for each post.
Here's the full, working version of your gatsby-node.js code:
const path = require('path'); exports.createPages = ({ graphql, boundActionCreators }) => { const { createPage } = boundActionCreators; return new Promise((resolve, reject) => { const blogPostTemplate = path.resolve('src/templates/blog-post.js'); resolve( graphql(` { allContentfulBlog(limit: 100) { edges { node { id slug # Add any other fields you need for your template here, e.g.: # title # publishedDate # body { # raw # } } } } } `).then(result => { if (result.errors) { // Reject the promise if GraphQL returns errors return reject(result.errors); } // Loop through each Contentful blog entry to create pages result.data.allContentfulBlog.edges.forEach((edge) => { createPage({ // Define clean URL using the slug from Contentful path: `/blog/${edge.node.slug}`, // Link to your post template component component: blogPostTemplate, // Pass post data to the template via context context: { id: edge.node.id, slug: edge.node.slug, }, }); }); resolve(); }) ); }); };
Key fixes and details:
- Added the missing iteration: We loop through every blog entry returned by the GraphQL query to generate a unique page for each post.
- Page configuration breakdown:
path: Uses theslugfield from your Contentful entries to create user-friendly URLs like/blog/my-first-post.component: Points to your post template file (double-check this file exists atsrc/templates/blog-post.js).context: Passes the post'sidandslugto the template, so you can fetch the full post data in the template's GraphQL query.
- Promise resolution: We call
resolve()after processing all posts to let Gatsby know page creation is complete. - Optional field expansion: I added comments for common fields you might want to fetch directly in this query (like title or publish date) if you need them for pre-processing.
Quick template example (blog-post.js):
To access the post data in your template, use a GraphQL query filtered by the slug passed via context:
import React from 'react'; import { graphql } from 'gatsby'; import { documentToReactComponents } from '@contentful/rich-text-react-renderer'; export const query = graphql` query($slug: String!) { contentfulBlog(slug: { eq: $slug }) { title publishedDate(formatString: "MMMM DD, YYYY") body { raw } } } `; const BlogPost = ({ data }) => { const post = data.contentfulBlog; return ( <div className="blog-post"> <h1>{post.title}</h1> <p className="post-date">{post.publishedDate}</p> <div className="post-content"> {documentToReactComponents(JSON.parse(post.body.raw))} </div> </div> ); }; export default BlogPost;
内容的提问来源于stack exchange,提问作者Isaac
相关产品推荐
相关产品推荐

