我正在使用Gatsby构建站点,到目前为止,我发现以编程方式创建页面非常方便。您可以拥有一个类别模板,并使gatsby-node非常轻松地为每个内容类别创建页面。
但是,将差异内容添加到同一模板的推荐方法是什么?
现在,我正在使用三元运算符来检查它是哪个类别,并基于该精确类别添加特定内容(需要相应区分的一些内容示例:基于SEO组件的类别介绍标题,SEO标题和SEO描述在 Helm 上)
在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
导入模板文件中,并让它决定通过prop选择哪个类别: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: https://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string
console.log("category:");
console.log(category);
// It is only one amazing line now!
return (
<CategoryIntro title={category.title} />
);
}
关于javascript - 在Gatsby JS中以编程方式创建页面时,如何区分某些内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57529305/