使用 Json 在 Gatsby 中以编程方式创建页面
Programatically creating pages in Gatsby using Json
我正在使用 gatsby 以编程方式创建页面,但我想在 2 个不同的路径 covers/{json.name}.js 和 styles/{json.name}.js 中这样做。
我已将其设置为当前使用 gatsby-node.js 文件工作,但更愿意使用 {} 约定来实现它们。目前在尝试 {}.js 方法时在两条路径上获取我的所有节点我的印象是使用此方法无法进行过滤,但目前是否有变通方法可以使其与上述方法一起使用。
没错,你说中要害了。实际上,使用 File System Route API. As you can see in the article feature announcement:
不可能使用 filters/custom 变量
Can I use custom variables for the file name?
Defining custom variables/fields inside the file isn’t possible at the
moment, e.g. if you want to use {something}.js
for your file name
and then define something as MarkdownRemark.fields__slug
. Therefore
you’ll have to follow the syntax of {Model.field__nestedField}
.
您的问题缺少规范,所以我不知道别名方法是否适合您(我猜不适合)。 Aliasing 允许您使用多个 gatsbyPath
,例如:
import React from "react"
import { Link, graphql } from "gatsby"
export default function HomePage(props) {
return (
<ul>
{props.data.allProduct.map(product => (
<li key={product.name}>
<Link to={product.productPath}>{product.name}</Link> (
<Link to={product.discountPath}>Discount</Link>)
</li>
))}
</ul>
)
}
export const query = graphql`
query {
allProduct {
name
productPath: gatsbyPath(filePath: "/products/{Product.name}")
discountPath: gatsbyPath(filePath: "/discounts/{Product.name}")
}
}
`
如果它不适合您,您将无法摆脱 gatsby-node.js
,因此文件系统 API 将不是一个有效的选择。
我正在使用 gatsby 以编程方式创建页面,但我想在 2 个不同的路径 covers/{json.name}.js 和 styles/{json.name}.js 中这样做。 我已将其设置为当前使用 gatsby-node.js 文件工作,但更愿意使用 {} 约定来实现它们。目前在尝试 {}.js 方法时在两条路径上获取我的所有节点我的印象是使用此方法无法进行过滤,但目前是否有变通方法可以使其与上述方法一起使用。
没错,你说中要害了。实际上,使用 File System Route API. As you can see in the article feature announcement:
不可能使用 filters/custom 变量Can I use custom variables for the file name?
Defining custom variables/fields inside the file isn’t possible at the moment, e.g. if you want to use
{something}.js
for your file name and then define something asMarkdownRemark.fields__slug
. Therefore you’ll have to follow the syntax of{Model.field__nestedField}
.
您的问题缺少规范,所以我不知道别名方法是否适合您(我猜不适合)。 Aliasing 允许您使用多个 gatsbyPath
,例如:
import React from "react"
import { Link, graphql } from "gatsby"
export default function HomePage(props) {
return (
<ul>
{props.data.allProduct.map(product => (
<li key={product.name}>
<Link to={product.productPath}>{product.name}</Link> (
<Link to={product.discountPath}>Discount</Link>)
</li>
))}
</ul>
)
}
export const query = graphql`
query {
allProduct {
name
productPath: gatsbyPath(filePath: "/products/{Product.name}")
discountPath: gatsbyPath(filePath: "/discounts/{Product.name}")
}
}
`
如果它不适合您,您将无法摆脱 gatsby-node.js
,因此文件系统 API 将不是一个有效的选择。