【问题标题】:How to render html code in strings of a Gatsby config file?如何在 Gatsby 配置文件的字符串中呈现 html 代码?
【发布时间】:2019-12-24 10:10:55
【问题描述】:

我了解 Gatsby 配置文件如何解析和解释 Markdown 文件,但我似乎不知道如何解析和解释 Gatsby 配置文件字符串中的内联 html。

举个例子,Victor Zhou 为他的博客做了这件事,他也使用了 Gatsby,你可以在第 6 行和第 28 行看到: https://github.com/vzhou842/victorzhou.com/blob/master/config.js

我想要一些字符串,例如:

author: {
    bio: 'I love <a href="https://google.com/">Google</a>'
}

最终呈现为(其中 Google 是指向“https://google.com/”的链接):

I love Google

但现在它只是呈现为:

I love <a href="https://google.com/">Google</a>

我认为解决方案非常简单明了,但由于某种原因,我一直坚持这一点,这真的很困扰我。

【问题讨论】:

    标签: javascript reactjs gatsby


    【解决方案1】:

    您可以通过先清理 html 然后将其注入元素来做到这一点。 例如:

    import sanitize from "sanitize-html"
    // For more info: https://www.npmjs.com/package/sanitize-html#what-are-the-default-options
    
    const whereYouWantToSanitize = (props) => {
      const htmlText = "Your <br /> <span class='red'>text</span>"
      const options = {
        allowedTags: ['br', 'span'],
        allowedAttributes: {
          br: ['class']
        }
      } //Check documentation for reference
      return (
        <YourComponentOrElement dangerouslySetInnerHTML={{
          __html: sanitizeHtml(htmlText, options)
        }} />
      )
    }
    

    【讨论】:

    • 不幸的是,我不认为这是清理 html 的问题。万一我误解了一些东西,我继续尝试你的建议,但它没有做任何事情。我认为这是 gatsby 如何获取配置文件、解析它并最终解释它的问题。我的直觉是有一些插件,就像我对 webpack 做的一样。但是看看 gatsby 配置插件,它们似乎都集中在最终渲染的内容上,而配置文件渲染似乎是一个更小众的问题?
    • 我试过了,它对我有用。您是否正确设置了options?因为您可能正在使用一些默认不支持的 html 元素以及一些属性,所以您必须指定它们。我将用一些options 更新我的答案,以便您了解它是如何工作的。
    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2013-03-11
    相关资源
    最近更新 更多