如何根据 Drupal JSON:API 响应中的术语关系在 Gatsby 中创建动态 URL?

How to create dynamic URL's in Gatsby from term relationships in Drupal JSON:API response?

我将 Drupal 8 用作无头 CMS,并使用 Gatsby 生成静态页面。

在 Drupal 中,我设置了一些节点类型(文章、图像、其他...)。所有实体都有 brandcategory 术语关系。

category是单选,brand是多选

Gatsby 在 URL 的赞上根据我的模板创建页面。

http://example.com/category-1/brand-1/
http://example.com/category-1/brand-2/
http://example.com/category-2/brand-1/
http://example.com/category-2/brand-2/

选中条目的文章和图像节点将显示在相应的 url 中。

我遇到的问题是,自从我将品牌术语更改为多项选择后,一些 URL 没有被创建。

因为field_brand[0].name Gatsby 只会为文章节点上的第一个品牌选择创建URL。

// gatsby-node.js

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions;
  const pageTemplate = path.resolve(`src/templates/pageTemplate.js`);
  return graphql(`
    {
      taxonomyTermBrand {
        field_colours
        name
      }
      allNodeImage {
        nodes {
          relationships {
            field_image_drop {
              uri {
                url
              }
            }
          }
        }
      }
      allNodeArticle {
        nodes {
          body {
            processed
          }
          relationships {
            field_brand {
              name
            }
            field_category {
              name
            }
          }
        }
      }
    }
  `, { limit: 1 }).then(result => {

    if (result.errors) {
      throw result.errors
    }

    result.data.allNodeArticle.nodes.forEach(node => {
      const brand_path = node.relationships.field_brand[0].name;
      const category_path = node.relationships.field_category.name;

      createPage({
        path: `${category_path}/${brand_path}`,
        component: pageTemplate,
        context: {
          brandName: node.relationships.field_brand[0].name,
          categoryName: node.relationships.field_category.name,
        },
      })
    })
  })
}

当数据传递给模板时,taxonomyTermBrand.name 的值基本上与 node.relationships.field_brand[0].name 相同,但我不能使用 taxonomyTermBrand.name,因为 pathcreatePageallNodeArticle.forEach()

是否有更好的方法或其他方法来设置路径并在这些页面上显示标记的内容?

我认为您可以针对每篇文章的每个 field_brand 项执行 forEach。

类似于:

result.data.allNodeArticle.nodes.forEach(node => {
  const brands = node.relationships.field_brand;
  const category = node.relationships.field_category.name;

  brands.forEach(brand => {
    createPage({
      path: `${category}/${brand.name}`,
      component: pageTemplate,
      context: {
        brandName: brand,
        categoryName: category,
      },
    })
  });
})