简体   繁体   English

Markdown 文件的客户端渲染

[英]Client-side rendering of a Markdown file

One can follow the Marked library documentation and render a Markdown string inline.可以按照标记库文档并内联呈现 Markdown 字符串。 This is a working code snippet.这是一个有效的代码片段。

 <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>

Is there a way to pass a file into the marked.parse function or through any other client-side Markdown rendering library and render the whole file instead of just a string?有没有办法将文件传递到marked.parse function 或通过任何其他客户端Markdown 渲染库并渲染整个文件而不仅仅是一个字符串? I looked into getting the markdown file and passing it as a string.我研究了获取 markdown 文件并将其作为字符串传递。 However, I couldn't find a straightforward way .但是,我找不到直接的方法

The file is in the same folder as this HTML file and would be served from GitHub using GitHub Pages.该文件与此 HTML 文件位于同一文件夹中,并将使用 GitHub 页面从 GitHub 提供。 However, I could use an absolute link from a CDN if needed.但是,如果需要,我可以使用来自 CDN 的绝对链接。 How would I pass the contents to marked.parse() ?我如何将内容传递给marked.parse() marked.parse(Hello.md) didn't work. marked.parse(Hello.md)不起作用。

The file is in the same folder as this HTML file and would be served from GitHub using GitHub Pages该文件与此 HTML 文件位于同一文件夹中,并将使用 GitHub 从 GitHub 提供

You can have the browser fetch the content and then pass its content to marked.parse() .您可以让浏览器fetch内容,然后将其内容传递给marked.parse() Something like this should work:像这样的东西应该工作:

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script defer>
  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 ra text into marked.parse
      document.getElementById("content").innerHTML = marked.parse(markdown);
    });
</script>

Here is a live example .这是一个活生生的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM