search
HomeWeb Front-endCSS TutorialHow to Make Taxonomy Pages With Gatsby and Sanity.io

How to Make Taxonomy Pages With Gatsby and Sanity.io

This tutorial will explain how to create a classification page using structured content from Gatsby and Sanity.io. You will learn how to create APIs using Gatsby's nodes Add fields to content types in Gatsby's GraphQL API. Specifically, we will create category pages for Sanity’s blog launcher.

It should be noted that the content introduced here has nothing to do with Sanity itself. You can do this no matter which content source you are using. We are using Sanity.io just for demonstration purposes.

Start a blog

If you want to learn this tutorial using your own Gatsby project, skip the section where you create a new page template in Gatsby. Otherwise, visit sanity.io/create and start the Gatsby blog launcher. It will put the code from the Sanity Studio and Gatsby front-end into your GitHub account and set up a deployment for both on Netlify. All configurations, including sample content, are ready so that you can start learning how to create a classification page directly.

After the project starts, make sure to clone the new GitHub repository locally and install the dependencies:

 git clone [email protected]:username/your-repository-name.git
cd your-repository-name
npm i

If you want to run both the Sanity Studio (CMS) and the Gatsby front-end locally, you can run the command npm run dev from the terminal in the project root directory. You can also go to the web folder and run Gatsby with the same command.

You should also install the Sanity CLI and log in to your account from the terminal: npm i -g @sanity/cli && sanity login . This will provide you with tools and useful commands to interact with your Sanity project. You can add the --help flag to get more information about its functions and commands.

We will make some customization to the gatsby-node.js file. To view the results of the changes, restart Gatsby's development server. This is done in most systems by pressing CTRL C in the terminal and running npm run dev again.

Familiar with content models

Check out the /studio/schemas/documents folder. Here are the schema files for our main content types: authors, categories, site settings, and posts. Each file exports a JavaScript object that defines fields and properties for these content types. In post.js is the field definition of the category:

 {
  name: 'categories',
  type: 'array',
  title: 'Categories',
  of: [
    {
      type: 'reference',
      to: [{
        type: 'category'
      }]
    }
  ]
},

This creates an array field with reference objects to the category document. In the blog's studio, it will look like this:

Add slug to category type

Go to /studio/schemas/documents/category.js . Category has a simple content model, which consists of titles and descriptions. Now we are creating a dedicated page for the category, and it is also convenient to have the slug field. We can define it in the architecture like this:

 // studio/schemas/documents/category.js
export default {
  name: 'category',
  type: 'document',
  title: 'Category',
  fields: [
    {
      name: 'title',
      type: 'string',
      title: 'Title'
    },
    {
      name: 'slug',
      type: 'slug',
      title: 'Slug',
      options: {
        // Add a button to generate slugs based on the title field
        source: 'title'
      }
    },
    {
      name: 'description',
      type: 'text',
      title: 'Description'
    }
  ]
}

Now that we have changed the content model, we need to update the GraphQL schema definition. Do this by doing npm run graphql-deploy (or sanity graphql deploy ) in the studio folder. You will receive a warning about the major changes, but since we've just added a field, you can keep going without worrying. If you want the field to be available in a studio on Netlify, check the changes into git (using git add . && git commit -m"add slug field" ) and push it to your GitHub repository ( git push origin master ).

Now we should browse the categories and generate slugs for them. Remember to click the Publish button to enable Gatsby to access these changes! If you are running Gatsby's development server, you will also need to restart it.

A brief description of how the Sanity source plugin works

When starting Gatsby in development or building a website, the source plug-in first gets the GraphQL schema definition from the GraphQL API deployed by Sanity. The source plugin uses it to tell Gatsby which fields should be available to prevent it from breaking when the contents of some fields disappear. It then accesses the project's export endpoint, which streams all accessible documents to Gatsby's in-memory data store.

In other words, the entire site is built with two requests. Running the development server will also set up a listener that pushes any changes from Sanity to Gatsby in real time without performing additional API queries. If we provide the source plugin with the token with read draft permission, we will see the changes immediately. This can also be experienced through Gatsby preview.

Add category page templates in Gatsby

Now that we have the GraphQL schema definition and some content, we can start creating category page templates in Gatsby. We need to do two things:

  • Tell Gatsby to create a page for the category node (this is the "document" term for Gatsby).
  • Provides Gatsby with a template file to generate HTML containing page data.

First open the /web/gatsby-node.js file. There is already code that can be used to create blog post pages. We will mainly use this code, but for categories. Let's go step by step:

Between the createBlogPostPages function and the line starting with exports.createPages , we can add the following code. I've added comments here to explain what's going on:

 // web/gatsby-node.js

// ...

async function createCategoryPages (graphql, actions) {
  // Get Gatsby method to create a new page const {createPage} = actions
  // Query Gatsby's GraphAPI to get all categories from Sanity // You can query this API at http://localhost:8000/___graphql
  const result = await graphql(`{
    allSanityCategory {
      nodes {
        slug {
          Current
        }
        id
      }
    }
  }
  `)
  // If there is any error in the query, cancel the build and tell us if (result.errors) throw result.errors

  // Let's gracefully handle the case where allSanityCatgogy is null const categoryNodes = (result.data.allSanityCategory || {}).nodes || []

  categoryNodes
    // Loop through the category nodes, but return nothing.forEach((node) => {
      // Deconstruct the id and slug fields of each category const {id, slug = {}} = node
      // If there is no slug, we do nothing if (!slug) return

      // Create URL with the current slug
      const path = `/categories/${slug.current}`

      // Create a page with URL path and template file and pass the id we can use to query the correct category in the template file
      createPage({
        path,
        component: require.resolve('./src/templates/category.js'),
        context: {id}
      })
    })
}

Finally, this function needs to be at the bottom of the file:

 // /web/gatsby-node.js

// ...

exports.createPages = async ({graphql, actions}) => {
  await createBlogPostPages(graphql, actions)
  await createCategoryPages(graphql, actions) // 
}

Now that we have the mechanism to create category page nodes, we need to add a template to show how it actually looks in the browser. We will get some consistent styles based on existing blog post templates, but keeping it fairly simple in the process.

 // /web/src/templates/category.js
import React from 'react'
import {graphql, Link} from 'gatsby'
import Container from '../components/container'
import GraphQLErrorList from '../components/graphql-error-list'
import SEO from '../components/seo'
import Layout from '../containers/layout'
import {getBlogUrl} from '../lib/helpers'


export const query = graphql`
  query CategoryTemplateQuery($id: String!) {
    category: sanityCategory(id: {eq: $id}) {
      title
      Description
      posts {
        _id
        title
        publishedAt
        slug {
          Current
        }
      }
    }
  }
`

const CategoryPostTemplate = props => {
  const {data = {}, errors} = props
  const {title, description, posts} = data.category || {}

  Return (
    <layout>
      <container>
        {errors &&<graphqlerrorlist errors="{errors}"></graphqlerrorlist> }
        {!data.category &&<p> No category data</p> }
        <seo title="{title}" description="{description}"></seo>
        <h1 id="Category-title">Category: {title}</h1>
        <p>{description}</p>
        {posts && (
          
            <h2 id="Posts">Posts</h2>
            <ul>
              {posts.map(post => (
                <li key="{post._id}">
                  <link to="{getBlogUrl(post.publishedAt," post.slug.current>{post.title}
                </li>
              ))}
            </ul>
          >
        )}
      </container>
    </layout>
  )
}

export default CategoryPostTemplate

This code will generate a simple category page with a list of linked posts – just like we want it!

Create a category page!

We just finished creating a new page type using a custom page template in Gatsby. We introduce a node API of Gatsby, called createResolver , and use it to add a new posts field to the category node.

This should give you what you need to create other types of classification pages! Do you have multiple authors on your blog? You can use the same logic to create author pages. What's interesting about GraphQL filters is that you can use it to go beyond explicit relationships created with references. It can also be used to match other fields using regular expressions or string comparisons. It's very flexible!

The above is the detailed content of How to Make Taxonomy Pages With Gatsby and Sanity.io. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Where should 'Subscribe to Podcast' link to?Where should 'Subscribe to Podcast' link to?Apr 16, 2025 pm 12:04 PM

For a while, iTunes was the big dog in podcasting, so if you linked "Subscribe to Podcast" to like:

Browser Engine DiversityBrowser Engine DiversityApr 16, 2025 pm 12:02 PM

We lost Opera when they went Chrome in 2013. Same deal with Edge when it also went Chrome earlier this year. Mike Taylor called these changes a "Decreasingly

UX Considerations for Web SharingUX Considerations for Web SharingApr 16, 2025 am 11:59 AM

From trashy clickbait sites to the most august of publications, share buttons have long been ubiquitous across the web. And yet it is arguable that these

Weekly Platform News: Apple Deploys Web Components, Progressive HTML Rendering, Self-Hosting Critical ResourcesWeekly Platform News: Apple Deploys Web Components, Progressive HTML Rendering, Self-Hosting Critical ResourcesApr 16, 2025 am 11:55 AM

In this week's roundup, Apple gets into web components, how Instagram is insta-loading scripts, and some food for thought for self-hosting critical resources.

Git Pathspecs and How to Use ThemGit Pathspecs and How to Use ThemApr 16, 2025 am 11:53 AM

When I was looking through the documentation of git commands, I noticed that many of them had an option for . I initially thought that this was just a

A Color Picker for Product ImagesA Color Picker for Product ImagesApr 16, 2025 am 11:49 AM

Sounds kind of like a hard problem doesn't it? We often don't have product shots in thousands of colors, such that we can flip out the with . Nor do we

A Dark Mode Toggle with React and ThemeProviderA Dark Mode Toggle with React and ThemeProviderApr 16, 2025 am 11:46 AM

I like when websites have a dark mode option. Dark mode makes web pages easier for me to read and helps my eyes feel more relaxed. Many websites, including

Some Hands-On with the HTML Dialog ElementSome Hands-On with the HTML Dialog ElementApr 16, 2025 am 11:33 AM

This is me looking at the HTML element for the first time. I've been aware of it for a while, but haven't taken it for a spin yet. It has some pretty cool and

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor