为 Gatsby Contentful 博客添加标签 [英] Adding tags to Gatsby Contentful blog

查看:43
本文介绍了为 Gatsby Contentful 博客添加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在博客文章中添加标签,但我很难找到解释如何实施它们的资源.

I'm trying to add tags on blog posts, and I struggle to find a resource, which explain how to implement them.

最终目标是获得可点击的标签,这会导致一个页面,其中所有具有相同标签的帖子都出现在一个列表中.

The end goal is to get clickable tags, which leads to a page, where all posts with same tag appears in a list.

我将 GatsbyJS 与 Contentful 集成一起使用.

I'm using GatsbyJS with Contentful integration.

我有一个名为 article-post.tsx 的文件,其中包含以下代码:

I have a file called article-post.tsx with the following code:

import React from "react"
import { graphql } from "gatsby"
import { documentToReactComponents } from "@contentful/rich-text-react-renderer"

import Layout from "../components/layout/layout"
import Img from "gatsby-image"
import SEO from "../components/layout/seo"
import styled from "styled-components"
import { BodyMain, H1 } from "../components/styles/TextStyles"

export const query = graphql`
  query($slug: String!) {
    contentfulArticlePost(slug: { eq: $slug }) {
      title
      tags
      publishedDate(formatString: "Do MMMM, YYYY")
      featuredImage {
        fluid(maxWidth: 720) {
          ...GatsbyContentfulFluid
        }
      }
      body {
        json
      }
    }
  }
`

const ArticlePost = props => {
  const options = {
    renderNode: {
      "embedded-asset-block": node => {
        const alt = node.data.target.fields.title["en-US"]
        const url = node.data.target.fields.file["en-US"].url
        return <img alt={alt} src={url} className="embeddedImage" />
      },
    },
  }

  return (
    <Layout>
      <SEO title={props.data.contentfulArticlePost.title} />
      <Wrapper>
        <ImageWrapper>
          {props.data.contentfulArticlePost.featuredImage && (
            <Img
              className="featured"
              fluid={props.data.contentfulArticlePost.featuredImage.fluid}
              alt={props.data.contentfulArticlePost.title}
            />
          )}
        </ImageWrapper>
        <Title>{props.data.contentfulArticlePost.title}</Title>
        <Tags>
          {props.data.contentfulArticlePost.tags.map(tag => (
            <span className="tag" key={tag}>
              {tag}
            </span>
          ))}
        </Tags>
        <ContentWrapper>
          {documentToReactComponents(
            props.data.contentfulArticlePost.body.json,
            options
          )}
        </ContentWrapper>
      </Wrapper>
    </Layout>
  )
}

export default ArticlePost

const Wrapper = styled.div`
  display: grid;
  grid-gap: 1.875rem;
  margin: 0 auto;
  padding: 7rem 1.875rem;
  max-width: 900px;
`

const ImageWrapper = styled.div`
  .featured {
    border-radius: 15px;
  }
`

const Title = styled(H1)`
  margin: 0 auto;
  text-align: center;
`

const Tags = styled.div`
margin: 0 auto;
.tag {
  background: #8636E4;
  border-radius: 1rem;
  padding: 0.5rem;
  margin: 0.2rem;
  font-weight: 600;
}
`

const ContentWrapper = styled(BodyMain)`
  display: grid;
  grid-gap: 20px;
  max-width: 900px;
  margin: 0 auto;
  line-height: 1.6;

  .embeddedImage {
    padding: 50px 0px;
    width: 100%;
    height: auto;
  }
`

它确实给了我标签,我可以设计它们.虽然我不知道如何让它们像链接/按钮一样可点击.

It does give me the tags and I'm able to style them. Though I don't know how to get them clickable like links/buttons.

我有一个名为 gatsby-node.js 的文件,其中包含以下代码:

I have a file called gatsby-node.js, which contains the following code:

const path = require("path")

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const response = await graphql(`
    query {
      allContentfulArticlePost {
        edges {
          node {
            id
            slug
          }
        }
      }
    }
  `)
  response.data.allContentfulArticlePost.edges.forEach(edge => {
    createPage({
      path: `/articles/${edge.node.slug}`,
      component: path.resolve("./src/templates/article-post.tsx"),
      context: {
        slug: edge.node.slug,
        id: edge.node.id
      },
    })
  })
}

我该往哪里去?

推荐答案

首先,您需要为每个标签创建动态页面以创建有效的链接元素.在您的 gatsby-node.js 中创建一个查询以获取所有标签并为每个标签创建页面,例如:

First of all, you need to create dynamic pages for each tag to create a valid link element. In your gatsby-node.js create a query to fetch all tags and create pages for each tag like:

const path = require("path")

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const response = await graphql(`
    query {
      allContentfulArticlePost {
        edges {
          node {
            id
            slug
          }
        }
      }
    }
  `)
  response.data.allContentfulArticlePost.edges.forEach(edge => {
    createPage({
      path: `/articles/${edge.node.slug}`,
      component: path.resolve("./src/templates/article-post.tsx"),
      context: {
        slug: edge.node.slug,
        id: edge.node.id
      },
    })
  })


  const tags= await graphql(`
    query {
      allContentfulArticlePost {
        edges {
          node {
            tags
          }
        }
      }
    }
  `)

  tags.data.allContentfulArticlePost.edges.forEach(edge=> {
   let slugifiedTag= edges.node.tag.toLowerCase().replace("/^\s+$/g", "-");

    createPage({
      path: `/tag/${slugifiedTag}`,
      component: path.resolve("./src/templates/tag-post.tsx"), // your tagComponent
      context: {
        slug: edge.node.slug,
        tagName: edges.node.tag
      },
    })
  })    
}

一步一步,首先,您需要在 tags 查询中从每个博客中检索所有标签.

Step by step, first of all, you need to retrieve all your tags from each blog in tags query.

然后,对于每个标签,您需要根据名称创建一个有效的 slug(即:This Is a Sample Tag 将转换为 this-is-a-sample-tagslugifiedTag 示例).这是在 edges.node.tag.toLowerCase().replace("/^\s+$/g", "-") 中完成的,正则表达式将匹配全空白全局并将它们替换为连字符 replace("/^\s+$/g", "-").您可能需要解析 tags 边缘以删除重复项以避免创建重复条目,创建一个 Set 应该适合你.

Then, for each tag, you need to create a valid slug based on the name (i.e: This Is a Sample Tag will be converted to this-is-a-sample-tag, slugifiedTag in the sample). This is done in edges.node.tag.toLowerCase().replace("/^\s+$/g", "-"), the regular expression will match all-white spaces globally and will replace them by hyphens replace("/^\s+$/g", "-"). You may need to parse the tags edge to remove duplicates in order to avoid duplicated entries creation, creating a Set should work for you.

此时,您将在 /tag/${slugifiedTag} 下创建所有页面(即:/tag/this-is-a-sample-tag).因此,您需要将 article-post.tsx 更改为指向标记页面:

At this point, you'll have created all pages under /tag/${slugifiedTag} (i.e: /tag/this-is-a-sample-tag). So, you will need to change your article-post.tsx to point to the tag page:

<Tags>
  {props.data.contentfulArticlePost.tags.map(tag => {
   let slugifiedTag= edges.node.tag.toLowerCase().replace("/^\s+$/g", "-");

    return <Link className="tag" key={tag} to={slugifiedTag}>
      {tag}
    </Link>
  })}
</Tags>

请注意,您正在重复 slugifiedTag 功能.您可以通过在 CMS 中创建标签实体并添加 nameslug 值来避免这种情况.如果您在 gatsby-node.js 查询以及模板查询中检索 slug,则可以直接指向 .按照这个例子,name 将是 This is a Sample Tagslug 将是直接的 this-is-a-sample-tag.

Note that you are repeating slugifiedTag function. You can avoid this by creating a tag entity in your CMS and adding a name and slug value. If you retrieve the slug in your gatsby-node.js query as well as in your template query, you can directly point to <Link className="tag" key={tag} to={tag.slug}>. Following this example, the name will be This is a Sample Tag while the slug will be direct this-is-a-sample-tag.

您最后要做的是在 tag-post.tsx 中创建一个查询,该查询获取每个标签的所有帖子,因为您通过上下文传递 slug 和 <代码>标签名称.您的查询应如下所示:

What you last is to create a query in your tag-post.tsx that fetch all posts for each tag since you are passing via context the slug and the tagName. Your query should look like:

export const query = graphql`
  query($slug: String!, $tags: [String!]) {
    contentfulArticlePost(slug: { eq: $slug }, tags: { in: $tags}) {
      title
      tags
      publishedDate(formatString: "Do MMMM, YYYY")
      featuredImage {
        fluid(maxWidth: 720) {
          ...GatsbyContentfulFluid
        }
      }
      body {
        json
      }
    }
  }
`

由于$tags 是一个数组,所以应该声明为[String!].如果您想让该字段不可为空,只需添加感叹号 (!),如 [String!]!.那么你只需要过滤包含至少一个标签的 by 标签:tags: { in: $tags}).

Since $tags is an array, should be declared as [String!]. If you want to make the field non-nullable just add the exclamation mark (!) like [String!]!. Then you only need to filter the by tags that contain at least one tag: tags: { in: $tags}).

正如我所说,这应该通过在您的 CMS 中添加一个带有 nameslug 字段的标签实体来改进和简化.

As I said, this should be improved and simplified by adding a tag entity in your CMS, with name and slug fields.

这是一个广泛的问题,无需了解您的数据结构和内部组件,但您已了解该方法的主要思想.

It's a broad question without knowing your data structure and your internal components but you get the main idea of the approach.

这篇关于为 Gatsby Contentful 博客添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆