[英]Passing variable into regex In Gatsby graphql query
I have the following query which is receiving the variable $tag
. 我有以下查询,它接收变量$tag
。 Currently I am filtering the results based on the value of its frontmatter.keywords
. 目前我正在根据其frontmatter.keywords
的值过滤结果。 keywords
is a comma separated string, so I need to use a regex to check for the inclusion of $tag
within it, however I can't work out how to pass the variable into the regex. keywords
是一个逗号分隔的字符串,所以我需要使用正则表达式来检查其中是否包含$tag
,但是我无法弄清楚如何将变量传递给正则表达式。 If I hardcode a value into the regex (as in the code below where I have hardcoded /example/
, the filtering works. If I replace example
with $tag
I receive an Error: 如果我将值硬编码到正则表达式中(如下面的代码,我有硬编码/example/
,过滤工作。如果我用$tag
替换example
,我收到一个错误:
GraphQLError: Variable "$tag" is never used in operation "TagQuery". GraphQLError:变量“$ tag”从未在“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
}
}
}
}
}
`;
How should I use $tag
within the regex? 我应该如何在正则表达式中使用$tag
?
I'd actually prefer to take a different approach and add the tags as an array in gatsby-node.js
, but there doesn't appear to be any way of filtering based on the value of the array. 我实际上更喜欢采用不同的方法并将标记作为数组添加到gatsby-node.js
,但似乎没有任何基于数组值的过滤方法。
我最终将标签拆分成一个数组,然后使用以下过滤器:
filter: { fields: { tags: { in: [$tag] } } }
Wherever you are passing $tag, just transform it to 无论你传递$ tag,只需将其转换为
const $tag = "\/".concat(tag).concat("\/")
But your error is specifically pointing to the fact that your query is not using the variable at all. 但是您的错误特别指出了您的查询根本没有使用该变量的事实。 So you'd also need to do 所以你也需要做
filter: { frontmatter: { keywords: { regex: $tag } } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.