【问题标题】:Is there any way to create dynamic slugs with Gatsby using a template component / page?有什么方法可以使用模板组件/页面使用 Gatsby 创建动态 slug?
【发布时间】:2020-04-03 16:32:55
【问题描述】:

我对 Gatsby 很陌生,我想知道我是否可以创建自定义路由(slugs)作为模板。用例是:

  1. 访问/articles/name-of-the-article路由
  2. 使用name-of-the-article slug 填充从 API(即 Strapi 无头 CMS)检索到的信息的服务组件 Article.js

【问题讨论】:

    标签: reactjs gatsby slug strapi


    【解决方案1】:

    经过一番调查,我发现使用gatsby-plugin-create-client-paths 有一种更简单的方法。 您需要做的就是使用yarnnpm 安装它,然后在gatsby-config.js 中添加这些:

    {
          resolve: `gatsby-plugin-create-client-paths`,
          options: { prefixes: [`/articles/*`] },
    },

    这意味着像这样的每个请求 slug:/articles/the-slug 将请求 articles.js 页面并使用 Gatsby 提供的 Link,您可以通过 state 传递 props,如下所示:

    <Link to="/articles/the-slug" state={{ slug: "the-slug", ...etc }}>Anchor Text</Link>

    这样src/pages/articles.js就变成了以/articles为前缀的slug的模板页面。

    【讨论】:

    • 有没有办法从articles.js 页面访问slug?例如,如果有人在地址栏中输入mywebsite.com/articles/some-article 而不是单击Link 组件,那么articles.js 页面组件是否可以在其props 中的某处访问some-article
    【解决方案2】:

    是的,你可以。盖茨比有这方面的文档:Creating pages from data programmatically。您需要创建页面 slug:Creating slugs for pages。您需要将gatsby-source-strapi 添加到您的gatsby-config.js

    我对 Strapi 几乎没有经验,因此您需要做一些研究如何使用 Strapi 处理 slug 创建。

    示例代码:

    gatsby-node.js
    
    exports.onCreateNode = ({ node, getNode, actions }) => {
      const { createNodeField } = actions;
      if (node.internal.type === "The Nodes as defined by Strapi") {
        const slug = createFilePath({ node, getNode, basePath: "The base paths as defined by Strapi" });
        createNodeField({ node, name: "slug", value: slug });
      }
    };
    
    exports.createPages = async function({ actions, graphql }) {
      const { data } = await graphql(`
    {
      allStrapiArticle {
        edges {
          node {
            id
            title
            content
          }
        }
      }
    }
      `)
      data.allMarkdownRemark.edges.forEach(edge => {
        const slug = edge.node.fields.slug
        actions.createPage({
          path: slug,
          component: require.resolve(`./src/templates/article-template.js`),
          context: { slug: slug },
        })
      })
    }
    

    【讨论】:

    • 使用 Strapi 处理 slug 非常容易,我也想在没有 GraphQL 的情况下管理它,因为我正在使用 REST 做所有事情。你觉得有可能吗?
    猜你喜欢
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2020-09-16
    • 2012-03-26
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多