nuxt.jsmarkdownnuxt-content

Getting Nuxt.js to generate routes from markdown frontmatter


I'm using nuxt-content to generate a static site from markdown files, and trying to figure out how to generate nested routes from frontmatter data. For example given a post's frontmatter:

title: Post Title
slug: post-title
media:
  - file: uploads/image_1.jpg
  - file: uploads/image_2.jpg

I would like to generate nested routes /posts/post-title/1 and /posts/post-title/2 for each media item listed in the frontmatter.

You can see my work in progress here. I have the functionality in place (click or key left/right arrows to navigate through posts and nested post media), but the nested routes have not been generated so these images are missing.

I presume I need to extend nuxt's route generator to parse the md frontmatter and loop through these items but have not been able to figure out how yet. Any help is much appreciated.


Solution

  • It turned out the solution was actually straightforward using Nuxt Content's method of specifying dynamic routes.

    Here is the complete function I used in nuxt.config to generate nested routes from the md frontmatter:

    generate: {
        async routes() {
          const { $content } = require('@nuxt/content')
          const works = await $content('works').only(['path', 'media']).fetch()
          const workMedia = []
          works.forEach(work => {
            if (work.media?.length > 1) {
              work.media.slice(1).forEach((e, i) => {
                workMedia.push(work.path + "/" + (i + 1))
              })
            }
          })
          return workMedia
        }
      }