【问题标题】:Client-side rendering of a Markdown fileMarkdown 文件的客户端渲染
【发布时间】:2021-11-30 03:57:03
【问题描述】:

可以按照Marked library documentation 并内联渲染 Markdown 字符串。这是一个工作代码 sn-p。

<div id="content"></div>
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script>
    document.getElementById('content').innerHTML =
      marked.parse('# Hello Ayan \n\nRendered by **marked**.');
  </script>

有没有办法将 文件 传递到 marked.parse 函数或通过 any other client-side Markdown rendering library 并呈现 整个文件 而不仅仅是一个字符串?我研究了获取降价文件并将其作为字符串传递。不过,我couldn't find a straightforward way

该文件与此 HTML 文件位于同一文件夹中,并将使用 GitHub Pages 从 GitHub 提供。但是,如果需要,我可以使用来自 CDN 的绝对链接。我如何将内容传递给marked.parse()marked.parse(Hello.md) 没用。

【问题讨论】:

  • 文件从哪里来?客户端 JavaScript 无法访问用户的文件系统。如果文件可以通过 HTTP 或类似方式获得,只需检索它并将其内容传递到 marked.parse()
  • 该文件与此 HTML 文件位于同一文件夹中,并将使用 GitHub Pages 从 GitHub 提供。但是,如果需要,我可以使用来自 CDN 的绝对链接。我如何将内容传递给marked.parse()marked.parse(Hello.md) 没用。

标签: markdown client-side html-rendering javascript-marked


【解决方案1】:

该文件与此 HTML 文件位于同一文件夹中,将使用 GitHub Pages 从 GitHub 提供

您可以让浏览器fetch 获取内容,然后将其内容传递给marked.parse()。像这样的东西应该可以工作:

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
  fetch("/pages-site/markdown.md")      // The path to the raw Markdown file
    .then(response => response.blob())  // Unwrap to a blob...
    .then(blob => blob.text())          // ...then to raw text...
    .then(markdown => {                 // ...then pass the raw text into marked.parse
      document.getElementById("content").innerHTML = marked.parse(markdown);
    });
</script>

Here is a live example.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2018-01-05
    • 2018-08-24
    相关资源
    最近更新 更多