【问题标题】:In Gatsbyjs, how to render markdown images when markdown is coming from a yaml object property?在 Gatsbyjs 中,当 markdown 来自 yaml 对象属性时,如何渲染 markdown 图像?
【发布时间】:2021-09-29 14:56:21
【问题描述】:

我正在使用一个 gatsbyjs 应用程序,其中我有一些具有以下格式的 .yml 文件:

我的目标是将 ma​​rkdownContent 字段的值呈现为 HTML。为此,我首先使用 'gatsby-transformer-yaml' 插件读取这些 .yml 文件的内容,然后使用 remarkremark-html 来转换ma​​rkdownContent 字段到 html。

html 渲染得很好,但是我无法渲染图像(链接为 markdownContent 字段的一部分)(所有图像请求都返回 404)

这种方式有可能吗?如果没有,当降价不是来自 gatsby-markdown-remark 时,如何让我的降价图像以 HTML 呈现?

【问题讨论】:

    标签: gatsby gatsby-image gatsby-plugin gatsby-remark-image


    【解决方案1】:

    您可以使用 gatsby-transformer-yaml-full 从 YAML 输入创建可查询的 GraphQL 节点。

    一旦安装(通过npm install gatsby-transformer-yaml-full 或其等效纱线):

    // gatsby-config.js
    
    module.exports = {
      plugins: [
        'gatsby-transformer-yaml-full',
        {
          resolve: 'gatsby-source-filesystem',
          options: {
            path: './content', // Path to your .yaml (or .yml) files
          },
        },
      ],
    }
    

    这将允许插件创建 GraphQL 节点,公开为 allCollectionYaml。例如:

    {
      allCollectionYaml {
        edges {
          node {
            character
            number
          }
        }
      }
    }
    

    然后在您的页面/模板中,您只需访问 GraphQL 数据(存储在页面props 中的data 对象中)并使用dangerouslySetInnerHTML 来呈现它:

    function MyComponent() {
      return <div dangerouslySetInnerHTML={{ __html: props.data.allCollectionYaml.edges.node[0].character}} />;
    }
    

    或者,您可以使用更安全的选项,例如 markdown-to-jsx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-23
      • 2019-08-23
      • 1970-01-01
      • 2021-11-10
      • 2023-04-10
      • 1970-01-01
      • 2021-12-14
      • 2017-09-11
      相关资源
      最近更新 更多