You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 the slug field 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 at src/templates/blog-post.js).
    • context: Passes the post's id and slug to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:25:07