gpt4 book ai didi

reactjs - 如何在 Gatsby 中查询特定语言的 markdown 文件?

转载 作者:行者123 更新时间:2023-12-04 02:40:51 25 4
gpt4 key购买 nike

我有一个文件夹content/projects,其中包含以下方式的文件:

  • project-a.de.md
  • project-a.en.md
  • project-b.de.md
  • project-b.en.md

现在我如何构建一个组件来显示其中的一些项目,这些项目在其 frontmatter 中具有 featured 标志并且使用特定语言?

我创建了以下组件:

import React from 'react'
import { FormattedMessage } from 'react-intl'
import { useStaticQuery, graphql } from 'gatsby'
import Content from '../Content'
import { FeaturedProjectsQuery } from '../../../graphql-types'

const FeaturedProjects: React.FC = () => {
const projects = useStaticQuery<FeaturedProjectsQuery>(graphql`
query FeaturedProjects {
allMarkdownRemark(filter: { fileAbsolutePath: { regex: "/(content/projects)/" }, frontmatter: { featured: { eq: true } } }) {
nodes {
frontmatter {
title
}
}
}
}
`)

return (
<Content>
<h2>
<FormattedMessage id="navigation.projects" />
</h2>
{projects.allMarkdownRemark.nodes.map(p => {
return <div>{p.frontmatter?.title}</div>
})}
</Content>
)
}

export default FeaturedProjects

这行得通,但我必须在 TypeScript 中过滤当前语言(我通过 React 上下文获取),尽管我认为这是 GraphQL 查询的完美任务,因为它是为选择事物而设计的。

不幸的是我不能在静态查询中使用变量。你将如何实现?

Tl;dr

我已尝试使用变量创建查询,但 graphql 标记中不允许进行字符串插值。

... 
allMarkdownRemark(filter: { fileAbsolutePath: {
regex: `/(content/projects).*\\.${lang}\\.md$/` ...
}
...

String interpolation is forbidden

最佳答案

好像string interpolation isn't supported - 太糟糕了!

你可以使用 gatsby-plugin-pathdatalang 字段添加到您的节点。

gatsby-config中,在plugins部分添加

{
resolve: "gatsby-plugin-pathdata",
options: {
matchNodeType: "MarkdownRemark",
extract: [
{
name: "lang",
// Regex isn't my strong suit so the `selector` might need some work
// This matches any 2 lower case letter, between 2 dots, followed by
// the `md` extension
// ====================
// ex: for `/path/to/the/file/project-b.de.md`, the `lang` field
// will be `de`
selector: /.+\/.*([a-z][a-z])+\.md$/,
replacer: "$1"
}
]
}
},

这会向您的所有 Markdown 文件添加一个 field.lang - 并且这些字段也可用于过滤。

有了它,您可以使用带有变量的查询来选择文件

query MyQuery($lang: String) {
allMarkdownRemark(filter: {fields: {lang: {eq: $lang}}}) {
nodes {
frontmatter {
title
}
}
}
}

可能还有其他方法可以得到它。

希望对您有所帮助!

关于reactjs - 如何在 Gatsby 中查询特定语言的 markdown 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com