如何在Gatsby中使用Directus?Directus数据在Gatsby.js中的调用方法
First, let's make sure you have the necessary tooling set up to pull data from Directus into Gatsby, then we'll finish your createPages function and build a template to render your posts.
1. Install & Configure the Gatsby Source Directus Plugin
Before your GraphQL queries will work, you need to install the official source plugin and link it to your Directus instance.
First, install the plugin:
npm install gatsby-source-directus --save # or yarn add gatsby-source-directus
Then add it to your gatsby-config.js file, replacing the placeholder values with your Directus details:
module.exports = { plugins: [ { resolve: `gatsby-source-directus`, options: { url: `https://your-directus-instance-url.com`, // Your Directus URL project: `_`, // Default is "_" for Directus Cloud; self-hosted might be your project name auth: { token: `your-directus-api-token`, // Optional if your collection is public }, }, }, ], }
Note: If your post collection is set to public (no authentication required), you can omit the auth object.
2. Complete the createPages Function
Your existing GraphQL query is on the right track—now we need to use the results to generate individual post pages. Here's the full implementation:
const path = require('path'); exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions; // Fetch all posts from Directus const result = await graphql(` { allDirectusPost { edges { node { id title # Add a slug field if you have one in Directus (recommended for clean URLs) # slug } } } } `); // Handle GraphQL errors if (result.errors) { throw result.errors; } // Define the path to your post template const postTemplate = path.resolve('./src/templates/post.js'); // Create a page for each post result.data.allDirectusPost.edges.forEach((edge) => { createPage({ path: `/posts/${edge.node.id}`, // Use slug instead of id if you have one: `/posts/${edge.node.slug}` component: postTemplate, context: { id: edge.node.id, // Pass the post ID to the template for querying }, }); }); };
Pro tip: Add a slug field to your Directus post collection (a text field with unique values) and use that in the path instead of the ID for more user-friendly URLs.
3. Create the Post Template Component
Now create a template file at src/templates/post.js to render each individual post. We'll use the post ID from the page context to fetch the full post data:
import React from 'react'; import { graphql } from 'gatsby'; export const query = graphql` query($id: String!) { directusPost(id: { eq: $id }) { title author content # Add any other fields you want to display (e.g., date, featured image) } } `; const PostTemplate = ({ data }) => { const post = data.directusPost; return ( <div className="post-container"> <h1>{post.title}</h1> <p className="author">By {post.author}</p> <div className="content" dangerouslySetInnerHTML={{ __html: post.content }} /> {/* Use dangerouslySetInnerHTML only if your content is HTML; if it's plain text, just use {post.content} */} </div> ); }; export default PostTemplate;
Note: If your content field in Directus is a rich text field, it will return HTML, hence using dangerouslySetInnerHTML. For plain text, just render it directly.
4. Test It Out
Run gatsby develop and navigate to http://localhost:8000/posts/[your-post-id]—you should see your post rendered! You can also use Gatsby's GraphiQL interface at http://localhost:8000/___graphql to test your queries and explore available fields.
内容的提问来源于stack exchange,提问作者key

