我有以下查询,它正在接收变量 $tag
。目前,我正在根据其 frontmatter.keywords
的值过滤结果。 keywords
是逗号分隔的字符串,所以我需要使用正则表达式来检查其中是否包含 $tag
,但是我不知道如何传递正则表达式中的变量。如果我将一个值硬编码到正则表达式中(如在下面的代码中我硬编码了 /example/
,则过滤有效。如果我将 example
替换为 $tag
我收到一个错误:
GraphQLError: Variable "$tag" is never used in operation "TagQuery".
export const pageQuery = graphql`
query TagQuery($tag: String) {
allMarkdownRemark(
limit: 100
sort: { fields: [frontmatter___date], order: DESC }
filter: { frontmatter: { keywords: { regex: "/example/" } } }
) {
totalCount
edges {
node {
fields {
slug
}
excerpt
frontmatter {
title
keywords
date
}
}
}
}
}
`;
我应该如何在正则表达式中使用 $tag
?
我实际上更喜欢采用不同的方法并将标签作为数组添加到 gatsby-node.js
中,但似乎没有任何方法可以根据值进行过滤数组的。
最佳答案
我最终将标签拆分成一个数组,然后使用以下内容进行过滤:
filter: { fields: { tags: { in: [$tag] } } }
关于javascript - 将变量传递给 Gatsby graphql 查询中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46933246/