在 Gatsby JS 中以编程方式创建页面时如何区分某些内容
How to differentiate some content when pages are created programmatically in Gatsby JS
我正在使用 Gatsby 构建站点,到目前为止,我发现以编程方式创建页面是一个非常方便的功能。您可以拥有一个类别模板,并让 gatsby-node 非常轻松地为每个内容类别创建页面。
但是,向同一模板添加差异化内容的推荐方法是什么?
现在我正在使用三元运算符来检查它是哪个类别,并根据该精确类别添加特定内容(需要相应区分的一些内容示例:类别介绍标题、SEO 标题和 SEO 描述在基于 Helmet 的 SEO 组件中)
里面categoryTemplate.js
const booksTitle = "Quote on books"
const songsTitle = "Quote on songs"
const travelsTitle = "Quote on travels"
const booksSeoTitle = "Books Title for SEO"
...
<CategoryIntro
title={<>
{category === "books"
? booksTitle
: category === "songs"
? songsTitle
: category === "travels"
? travelsTitle
: null
}
</>}
/>
这种方法确实有效,但我想知道是否有更方便的做法可以使用?我是否应该以 json 格式在别处存储有关类别的信息,而不是在模板文件中声明它们?
非常感谢。
我认为您建议的将信息存储在别处的方法会使代码更清晰,更易于维护。模板组件应该只是一个通用模板,因为它是预期的。你不应该把它和内容混在一起。
categories.js
文件怎么样?
export const categories = {
book: {
title: "Quote on books",
seoTitle: "",
},
songs: {
title: "Quote on songs",
seoTitle: "",
},
}
在您的模板文件中导入您的 categories.js
并让它通过道具决定选择哪个类别:
import { categories } from "./categories.js"
// This function returns your mediaType object
function getObject(obj, mediaType) {
return obj[mediaType];
}
function MediaTemplate({ mediaType }) {
const category = getObject(mediaType);
// See this answer for how to access the object key dynamically:
console.log("category:");
console.log(category);
// It is only one amazing line now!
return (
<CategoryIntro title={category.title} />
);
}
我正在使用 Gatsby 构建站点,到目前为止,我发现以编程方式创建页面是一个非常方便的功能。您可以拥有一个类别模板,并让 gatsby-node 非常轻松地为每个内容类别创建页面。 但是,向同一模板添加差异化内容的推荐方法是什么?
现在我正在使用三元运算符来检查它是哪个类别,并根据该精确类别添加特定内容(需要相应区分的一些内容示例:类别介绍标题、SEO 标题和 SEO 描述在基于 Helmet 的 SEO 组件中)
里面categoryTemplate.js
const booksTitle = "Quote on books"
const songsTitle = "Quote on songs"
const travelsTitle = "Quote on travels"
const booksSeoTitle = "Books Title for SEO"
...
<CategoryIntro
title={<>
{category === "books"
? booksTitle
: category === "songs"
? songsTitle
: category === "travels"
? travelsTitle
: null
}
</>}
/>
这种方法确实有效,但我想知道是否有更方便的做法可以使用?我是否应该以 json 格式在别处存储有关类别的信息,而不是在模板文件中声明它们?
非常感谢。
我认为您建议的将信息存储在别处的方法会使代码更清晰,更易于维护。模板组件应该只是一个通用模板,因为它是预期的。你不应该把它和内容混在一起。
categories.js
文件怎么样?
export const categories = {
book: {
title: "Quote on books",
seoTitle: "",
},
songs: {
title: "Quote on songs",
seoTitle: "",
},
}
在您的模板文件中导入您的 categories.js
并让它通过道具决定选择哪个类别:
import { categories } from "./categories.js"
// This function returns your mediaType object
function getObject(obj, mediaType) {
return obj[mediaType];
}
function MediaTemplate({ mediaType }) {
const category = getObject(mediaType);
// See this answer for how to access the object key dynamically:
console.log("category:");
console.log(category);
// It is only one amazing line now!
return (
<CategoryIntro title={category.title} />
);
}