【问题标题】:Getting Nuxt.js to generate routes from markdown frontmatter让 Nuxt.js 从 markdown frontmatter 生成路由
【发布时间】:2023-03-03 17:16:01
【问题描述】:

我使用nuxt-content 从markdown 文件生成一个静态站点,并试图弄清楚如何从frontmatter 数据生成嵌套路由。例如给定一个帖子的frontmatter:

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

我想为 frontmatter 中列出的每个媒体项生成嵌套路由 /posts/post-title/1/posts/post-title/2

你可以看到我的work in progress here。我有适当的功能(单击或键左/右箭头以浏览帖子和嵌套的帖子媒体),但尚未生成嵌套路由,因此这些图像丢失了。

我想我需要扩展 nuxt 的路由生成器来解析 md frontmatter 并遍历这些项目,但还没有弄清楚如何。非常感谢任何帮助。

【问题讨论】:

    标签: nuxt.js markdown nuxt-content


    【解决方案1】:

    事实证明,使用 Nuxt Content 的 specifying dynamic routes 方法,解决方案实际上很简单。

    这是我在 nuxt.config 中使用的完整函数,用于从 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
        }
      }
    

    【讨论】:

      【解决方案2】:

      您似乎需要一个自定义解析器,如下所述:https://github.com/nuxt/content/issues/191#issuecomment-661096025

      这里有一个解决方案:https://github.com/nuxt/content/issues/214#issuecomment-656759077

      this.nuxt.hook('content:file:beforeInsert', function (document) {
        // document.items
      })
      

      【讨论】:

      • 感谢您的提示。我无法弄清楚如何使用该特定解决方案,但我最终找到了一种在 config generate hook 中使用 nuxt-content 的方法。
      猜你喜欢
      • 2021-03-12
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 2015-03-29
      • 2019-06-25
      • 2021-06-23
      • 1970-01-01
      相关资源
      最近更新 更多