现在为博客添加标签,方便查看同标签的其它博客。
npm install yarn -g
yarn add gatsby-plugin-tags
在 gatsby-config.js 的 plugins 中添加:
{
resolve: "gatsby-plugin-tags",
options: {
templatePath: `${__dirname}/src/templates/tag.js`,
},
},
参考 https://github.com/rmcfadzean/gatsby-pantry/tree/master/examples/starter-blog
做了适当的修改。
(1) 添加组件
src/components/PostsListCard.js
import React from "react"
import { Link } from "gatsby"
import { rhythm } from "../utils/typography"
const PostsListCard = ({ frontmatter, fields, excerpt }) => {
const title = frontmatter.title || fields.slug
return (
<article key={fields.slug}>
<header>
<h3
style={{
marginBottom: rhythm(1 / 4),
}}
>
<Link style={{ boxShadow: `none` }} to={fields.slug}>
{title}
</Link>
</h3>
<small>{frontmatter.date}</small>
</header>
<section>
<p
dangerouslySetInnerHTML={{
__html: frontmatter.description || excerpt,
}}
/>
</section>
</article>
)
}
export default PostsListCard
src/components/PostsList.js
import React from "react"
import PostsListCard from "./PostsListCard"
const PostsList = ({ postEdges }) => {
return postEdges.map(({ node }) => {
return <PostsListCard key={node.fields.slug} {...node} />
})
}
export default PostsList
(2) 添加标签页
src/templates/tag.js
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"
import PostsList from "../components/PostsList"
const CategoryTemplate = ({ location, pageContext, data }) => {
const { tag } = pageContext
const siteTitle = "谛听的博客"
return (
<Layout location={location} title={siteTitle}>
<div className="tag-container">
<SEO title={`${tag}`} />
<h1>{tag}</h1>
<PostsList postEdges={data.allMarkdownRemark.edges} />
</div>
</Layout>
)
}
export const pageQuery = graphql`
query TagPage($tag: String) {
allMarkdownRemark(
limit: 1000
filter: { fields: { tags: { in: [$tag] } } }
) {
totalCount
edges {
node {
fields {
slug
tags
}
excerpt
timeToRead
frontmatter {
title
date
}
}
}
}
}
`
export default CategoryTemplate
(3) 修改博客模版页面
src/templates/blog-post.js 中合适的地方分别添加以下三段代码:
import style from "../styles/blog.module.css"
<div>
{post.fields.tags && (
<div>
{post.fields.tags.map(tag => (
<Link
to={`/tags/${tag}`}
className={style.tag}
>
{tag}
</Link>
))}
</div>
)}
</div>
export const pageQuery = graphql`
query BlogPostBySlug($slug: String!) {
site {
siteMetadata {
title
author
}
}
markdownRemark(fields: { slug: { eq: $slug } }) {
id
excerpt(pruneLength: 160)
html
frontmatter {
title
date
}
fields {
tags
}
}
}
`
(4) 添加标签样式
src/styles/blog.module.css
.tag {
margin-right: 2%;
}
(5) 在 content/blog 中每篇博客的开头添加标签:
tags:
- 标签1
- 标签2
如果没有自动重建,手动执行:
gatsby build
效果:https://aping-dev.com/gatsby-tags/
gatsby-plugin-tags. https://www.gatsbyjs.org/packages/gatsby-plugin-tags/?=tag
https://github.com/rmcfadzean/gatsby-pantry/tree/master/examples/starter-blog
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。