👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

How to get slugs from parent documents in Sanity Studio using custom slugify function.

6 replies
Last updated: Jan 26, 2022
Is there a method in the Studio to get the slugs from all parent documents?
I have a nested structure of
/:module/:chapter/:section
and I’d like to get the chapter and module slugs when fetching the section
Jan 25, 2022, 11:33 PM
I think the best approach would be to create a custom slugify function that does this for you. There's not a neat and tidy way to do it, though. If it's set up that the section references a chapter, which then references a module, the following will work:
*Note: you will need to install slugify and import the sanity client for this to work.


{
      name: 'slugWithPath',
      title: 'Slug with Path',
      group: 'community',
      options: {
        source: '_id',
        slugify: async (input) => {
          const query = `*[_id match $id][0]{ 
            title,
            'chapterSlug': chapter->.slug.current,
            'moduleSlug': chapter->.module->.slug.current
          }`
          const document = await sanityClient
            .fetch(query, { id: `**${input}`})
          
          const {
            title,
            chapterSlug,
            moduleSlug
          } = document
          
          return `${moduleSlug}/${chapterSlug}/${slugify(title, { lower: true })}`
        }
      }
    }
Jan 26, 2022, 12:56 AM
Thanks
user M
, I’ll give this a try
Jan 26, 2022, 1:33 AM
Just for fun, you could also assemble the path with GROQ:

*[ _id == "section" ][0] {
  ...*[_type == "chapter" && references(^._id)][0]
  {
    "slug": *[_type == "module" && references(^._id)][0].slug + '/' + slug + '/' + ^.slug
  },
}

https://groq.dev/SRHr6fRV7Q1gxX9BuHxN7i
Jan 26, 2022, 8:00 AM
Thanks
user G
Your code samples have helped me realize how powerful GROQ is
Jan 26, 2022, 4:09 PM
That query as part of
user M
’s slugify code is probably exactly what I need
Jan 26, 2022, 4:12 PM
One note for anyone else looking to use something like this — it needs to reference
slug.current
rather than just
slug
— This gets the full route for my schema setup
*[ _type == "section" ][0] {
  ...*[_type == "chapter" && references(^._id)][0]
  {
    "slug": *[_type == "module" && references(^._id)][0].slug.current + '/' + slug.current + '/' + ^.slug.current
  },
}
Jan 26, 2022, 4:13 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?