Gatsby: Markdown中的变量?

创建于 2018-11-28  ·  1评论  ·  资料来源: gatsbyjs/gatsby

概要

有没有一种方法可以在降价页面中将变量替换为值? 我正在写有关服务的文档(URL)。 该URL位于几个markdown文件中,我希望不必查找和替换它以防万一。

我最好的选择是在Markdown中添加自定义组件吗? 这似乎是徒劳的。

question or discussion

最有用的评论

您可以为此编写一个小的自定义帮助程序(或使用类似lodash.template https://lodash.com/docs/4.17.11#template的东西)

这是一个快速而肮脏的解决方案:

给定一个降价文件sample.md ,其内容如下:

---
title: Sample
---

## Hello World

This is a [link](%URL%/sub-path), and so is [this](%URL%/sub-path)

您可以创建一个文件(我们称它为src/utils/template.js )并编写如下内容

export default function template(content, data) {
  return content.replace(/%(.+)%/g, (match, key) => {
    const value = data[key]
    if (typeof value !== 'undefined') {
      return value
    }
    return match // guards against some unintentional prefix
  });
}

现在将所有内容连接在一起,您只需_use_此模板函数即可替换您的内容。 data对象可以是您想要的任何对象,并且可以从任何地方拖动(例如graphql,一些常量文件,环境变量等)。

import React from 'react'

import template from '../utils/template';

const URL = 'https://google.com'; // this can be from wherever

export default function SomeMarkdownPage({ data }) {
  // data is from GraphQL, presume the parent is data.markdown
  return (
    <div dangerouslySetInnerHTML={{
      __html: template(data.markdown.html, {
        URL
      })
    }} />
  )
}

这有意义吗? 这也可能是一个相当有用的gatsby-remark-插件,但是我不确定它是否存在! 如果您对此有兴趣,那太酷了,但是就目前而言,这肯定适合您的用例!

将按照回答将其关闭,但是如果我们中的任何一个可以帮助您,请随时重新打开。 感谢您使用盖茨比!

>所有评论

您可以为此编写一个小的自定义帮助程序(或使用类似lodash.template https://lodash.com/docs/4.17.11#template的东西)

这是一个快速而肮脏的解决方案:

给定一个降价文件sample.md ,其内容如下:

---
title: Sample
---

## Hello World

This is a [link](%URL%/sub-path), and so is [this](%URL%/sub-path)

您可以创建一个文件(我们称它为src/utils/template.js )并编写如下内容

export default function template(content, data) {
  return content.replace(/%(.+)%/g, (match, key) => {
    const value = data[key]
    if (typeof value !== 'undefined') {
      return value
    }
    return match // guards against some unintentional prefix
  });
}

现在将所有内容连接在一起,您只需_use_此模板函数即可替换您的内容。 data对象可以是您想要的任何对象,并且可以从任何地方拖动(例如graphql,一些常量文件,环境变量等)。

import React from 'react'

import template from '../utils/template';

const URL = 'https://google.com'; // this can be from wherever

export default function SomeMarkdownPage({ data }) {
  // data is from GraphQL, presume the parent is data.markdown
  return (
    <div dangerouslySetInnerHTML={{
      __html: template(data.markdown.html, {
        URL
      })
    }} />
  )
}

这有意义吗? 这也可能是一个相当有用的gatsby-remark-插件,但是我不确定它是否存在! 如果您对此有兴趣,那太酷了,但是就目前而言,这肯定适合您的用例!

将按照回答将其关闭,但是如果我们中的任何一个可以帮助您,请随时重新打开。 感谢您使用盖茨比!

此页面是否有帮助?
0 / 5 - 0 等级