markdown-to-html

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Markdown to HTML Conversion

Markdown转HTML转换

Expert skill for converting Markdown documents to HTML using the marked.js library, or writing data conversion scripts; in this case scripts similar to markedJS/marked repository. For custom scripts knowledge is not confined to
marked.js
, but data conversion methods are utilized from tools like pandoc and gomarkdown/markdown for data conversion; jekyll/jekyll and gohugoio/hugo for templating systems.
The conversion script or tool should handle single files, batch conversions, and advanced configurations.
本技能可使用marked.js库将Markdown文档转换为HTML,或编写数据转换脚本;此处的脚本与markedJS/marked仓库中的脚本类似。自定义脚本的知识不限于
marked.js
,还可借鉴pandocgomarkdown/markdown等工具的数据转换方法,以及jekyll/jekyllgohugoio/hugo等模板系统的实现。
转换脚本或工具应支持单文件转换、批量转换及高级配置。

When to Use This Skill

何时使用本技能

  • User asks to "convert markdown to html" or "transform md files"
  • User wants to "render markdown" as HTML output
  • User needs to generate HTML documentation from .md files
  • User is building static sites from Markdown content
  • User is building template system that converts markdown to html
  • User is working on a tool, widget, or custom template for an existing templating system
  • User wants to preview Markdown as rendered HTML
  • 用户要求“将markdown转为html”或“转换md文件”
  • 用户希望将markdown渲染为HTML输出
  • 用户需要从.md文件生成HTML文档
  • 用户基于Markdown内容构建静态站点
  • 用户开发将Markdown转换为HTML的模板系统
  • 用户为现有模板系统开发工具、组件或自定义模板
  • 用户希望预览Markdown渲染后的HTML效果

Converting Markdown to HTML

Markdown转HTML转换方法

Essential Basic Conversions

基础转换示例

For more see basic-markdown-to-html.md
text
    ```markdown
    # Level 1
    ## Level 2

    One sentence with a [link](https://example.com), and a HTML snippet like `<p>paragraph tag</p>`.

    - `ul` list item 1
    - `ul` list item 2

    1. `ol` list item 1
    2. `ol` list item 1

    | Table Item | Description |
    | One | One is the spelling of the number `1`. |
    | Two | Two is the spelling of the number `2`. |

    ```js
    var one = 1;
    var two = 2;

    function simpleMath(x, y) {
     return x + y;
    }
    console.log(simpleMath(one, two));
    ```
    ```

    ```html
    <h1>Level 1</h1>
    <h2>Level 2</h2>

    <p>One sentence with a <a href="https://example.com">link</a>, and a HTML snippet like <code>&lt;p&gt;paragraph tag&lt;/p&gt;</code>.</p>

    <ul>
     <li>`ul` list item 1</li>
     <li>`ul` list item 2</li>
    </ul>

    <ol>
     <li>`ol` list item 1</li>
     <li>`ol` list item 2</li>
    </ol>

    <table>
     <thead>
      <tr>
       <th>Table Item</th>
       <th>Description</th>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td>One</td>
       <td>One is the spelling of the number `1`.</td>
      </tr>
      <tr>
       <td>Two</td>
       <td>Two is the spelling of the number `2`.</td>
      </tr>
     </tbody>
    </table>

    <pre>
     <code>var one = 1;
     var two = 2;

     function simpleMath(x, y) {
      return x + y;
     }
     console.log(simpleMath(one, two));</code>
    </pre>
    ```
更多内容请查看basic-markdown-to-html.md
text
    ```markdown
    # 一级标题
    ## 二级标题

    这是一段包含[链接](https://example.com)的文字,还有一段HTML片段:`<p>段落标签</p>`。

    - 无序列表项1
    - 无序列表项2

    1. 有序列表项1
    2. 有序列表项2

    | 表格项 | 描述 |
    | --- | --- |
    | One | 数字`1`的英文拼写 |
    | Two | 数字`2`的英文拼写 |

    ```js
    var one = 1;
    var two = 2;

    function simpleMath(x, y) {
     return x + y;
    }
    console.log(simpleMath(one, two));
    ```
    ```

    ```html
    <h1>一级标题</h1>
    <h2>二级标题</h2>

    <p>这是一段包含<a href="https://example.com">链接</a>的文字,还有一段HTML片段:<code>&lt;p&gt;段落标签&lt;/p&gt;</code>。</p>

    <ul>
     <li>无序列表项1</li>
     <li>无序列表项2</li>
    </ul>

    <ol>
     <li>有序列表项1</li>
     <li>有序列表项2</li>
    </ol>

    <table>
     <thead>
      <tr>
       <th>表格项</th>
       <th>描述</th>
      </tr>
     </thead>
     <tbody>
      <tr>
       <td>One</td>
       <td>数字`1`的英文拼写</td>
      </tr>
      <tr>
       <td>Two</td>
       <td>数字`2`的英文拼写</td>
      </tr>
     </tbody>
    </table>

    <pre>
     <code>var one = 1;
     var two = 2;

     function simpleMath(x, y) {
      return x + y;
     }
     console.log(simpleMath(one, two));</code>
    </pre>
    ```

Code Block Conversions

代码块转换示例

For more see code-blocks-to-html.md
text

    ```markdown
    your code here
    ```

    ```html
    <pre><code class="language-md">
    your code here
    </code></pre>
    ```

    ```js
    console.log("Hello world");
    ```

    ```html
    <pre><code class="language-js">
    console.log("Hello world");
    </code></pre>
    ```

    ```markdown
      ```

      ```
      visible backticks
      ```

      ```
    ```

    ```html
      <pre><code>
      ```

      visible backticks

      ```
      </code></pre>
    ```
更多内容请查看code-blocks-to-html.md
text

    ```markdown
    your code here
    ```

    ```html
    <pre><code class="language-md">
    your code here
    </code></pre>
    ```

    ```js
    console.log("Hello world");
    ```

    ```html
    <pre><code class="language-js">
    console.log("Hello world");
    </code></pre>
    ```

    ```markdown
      ```

      ```
      visible backticks
      ```

      ```
    ```

    ```html
      <pre><code>
      ```

      visible backticks

      ```
      </code></pre>
    ```

Collapsed Section Conversions

折叠区块转换示例

For more see collapsed-sections-to-html.md
text
    ```markdown
    <details>
    <summary>More info</summary>

    ### Header inside

    - Lists
    - **Formatting**
    - Code blocks

        ```js
        console.log("Hello");
        ```

    </details>
    ```

    ```html
    <details>
    <summary>More info</summary>

    <h3>Header inside</h3>

    <ul>
     <li>Lists</li>
     <li><strong>Formatting</strong></li>
     <li>Code blocks</li>
    </ul>

    <pre>
     <code class="language-js">console.log("Hello");</code>
    </pre>

    </details>
    ```
更多内容请查看collapsed-sections-to-html.md
text
    ```markdown
    <details>
    <summary>更多信息</summary>

    ### 内部标题

    - 列表项
    - **加粗格式**
    - 代码块

        ```js
        console.log("Hello");
        ```

    </details>
    ```

    ```html
    <details>
    <summary>更多信息</summary>

    <h3>内部标题</h3>

    <ul>
     <li>列表项</li>
     <li><strong>加粗格式</strong></li>
     <li>代码块</li>
    </ul>

    <pre>
     <code class="language-js">console.log("Hello");</code>
    </pre>

    </details>
    ```

Mathematical Expression Conversions

数学表达式转换示例

For more see writing-mathematical-expressions-to-html.md
text
    ```markdown
    This sentence uses `$` delimiters to show math inline: $\sqrt{3x-1}+(1+x)^2$
    ```

    ```html
    <p>This sentence uses <code>$</code> delimiters to show math inline:
     <math-renderer><math xmlns="http://www.w3.org/1998/Math/MathML">
      <msqrt><mn>3</mn><mi>x</mi><mo>−</mo><mn>1</mn></msqrt>
      <mo>+</mo><mo>(</mo><mn>1</mn><mo>+</mo><mi>x</mi>
      <msup><mo>)</mo><mn>2</mn></msup>
     </math>
    </math-renderer>
    </p>
    ```

    ```markdown
    **The Cauchy-Schwarz Inequality**\
    $$\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)$$
    ```

    ```html
    <p><strong>The Cauchy-Schwarz Inequality</strong><br>
     <math-renderer>
      <math xmlns="http://www.w3.org/1998/Math/MathML">
       <msup>
        <mrow><mo>(</mo>
         <munderover><mo data-mjx-texclass="OP">∑</mo>
          <mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi>
         </munderover>
         <msub><mi>a</mi><mi>k</mi></msub>
         <msub><mi>b</mi><mi>k</mi></msub>
         <mo>)</mo>
        </mrow>
        <mn>2</mn>
       </msup>
       <mo>≤</mo>
       <mrow><mo>(</mo>
        <munderover><mo>∑</mo>
         <mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow>
         <mi>n</mi>
        </munderover>
        <msubsup><mi>a</mi><mi>k</mi><mn>2</mn></msubsup>
        <mo>)</mo>
       </mrow>
       <mrow><mo>(</mo>
         <munderover><mo>∑</mo>
          <mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow>
          <mi>n</mi>
         </munderover>
         <msubsup><mi>b</mi><mi>k</mi><mn>2</mn></msubsup>
         <mo>)</mo>
       </mrow>
      </math>
     </math-renderer></p>
    ```
更多内容请查看writing-mathematical-expressions-to-html.md
text
    ```markdown
    这句话使用`$`分隔符展示行内数学公式:$\sqrt{3x-1}+(1+x)^2$
    ```

    ```html
    <p>这句话使用<code>$</code>分隔符展示行内数学公式:
     <math-renderer><math xmlns="http://www.w3.org/1998/Math/MathML">
      <msqrt><mn>3</mn><mi>x</mi><mo>−</mo><mn>1</mn></msqrt>
      <mo>+</mo><mo>(</mo><mn>1</mn><mo>+</mo><mi>x</mi>
      <msup><mo>)</mo><mn>2</mn></msup>
     </math>
    </math-renderer>
    </p>
    ```

    ```markdown
    **柯西-施瓦茨不等式**\
    $$\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)$$
    ```

    ```html
    <p><strong>柯西-施瓦茨不等式</strong><br>
     <math-renderer>
      <math xmlns="http://www.w3.org/1998/Math/MathML">
       <msup>
        <mrow><mo>(</mo>
         <munderover><mo data-mjx-texclass="OP">∑</mo>
          <mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi>
         </munderover>
         <msub><mi>a</mi><mi>k</mi></msub>
         <msub><mi>b</mi><mi>k</mi></msub>
         <mo>)</mo>
        </mrow>
        <mn>2</mn>
       </msup>
       <mo>≤</mo>
       <mrow><mo>(</mo>
        <munderover><mo>∑</mo>
         <mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow>
         <mi>n</mi>
        </munderover>
        <msubsup><mi>a</mi><mi>k</mi><mn>2</mn></msubsup>
        <mo>)</mo>
       </mrow>
       <mrow><mo>(</mo>
         <munderover><mo>∑</mo>
          <mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow>
          <mi>n</mi>
         </munderover>
         <msubsup><mi>b</mi><mi>k</mi><mn>2</mn></msubsup>
         <mo>)</mo>
       </mrow>
      </math>
     </math-renderer></p>
    ```

Table Conversions

表格转换示例

For more see tables-to-html.md
text
    ```markdown
    | First Header  | Second Header |
    | ------------- | ------------- |
    | Content Cell  | Content Cell  |
    | Content Cell  | Content Cell  |
    ```

    ```html
    <table>
     <thead><tr><th>First Header</th><th>Second Header</th></tr></thead>
     <tbody>
      <tr><td>Content Cell</td><td>Content Cell</td></tr>
      <tr><td>Content Cell</td><td>Content Cell</td></tr>
     </tbody>
    </table>
    ```

    ```markdown
    | Left-aligned | Center-aligned | Right-aligned |
    | :---         |     :---:      |          ---: |
    | git status   | git status     | git status    |
    | git diff     | git diff       | git diff      |
    ```

    ```html
    <table>
      <thead>
       <tr>
        <th align="left">Left-aligned</th>
        <th align="center">Center-aligned</th>
        <th align="right">Right-aligned</th>
       </tr>
      </thead>
      <tbody>
       <tr>
        <td align="left">git status</td>
        <td align="center">git status</td>
        <td align="right">git status</td>
       </tr>
       <tr>
        <td align="left">git diff</td>
        <td align="center">git diff</td>
        <td align="right">git diff</td>
       </tr>
      </tbody>
    </table>
    ```
更多内容请查看tables-to-html.md
text
    ```markdown
    | 第一列标题 | 第二列标题 |
    | --- | --- |
    | 内容单元格 | 内容单元格 |
    | 内容单元格 | 内容单元格 |
    ```

    ```html
    <table>
     <thead><tr><th>第一列标题</th><th>第二列标题</th></tr></thead>
     <tbody>
      <tr><td>内容单元格</td><td>内容单元格</td></tr>
      <tr><td>内容单元格</td><td>内容单元格</td></tr>
     </tbody>
    </table>
    ```

    ```markdown
    | 左对齐 | 居中对齐 | 右对齐 |
    | :--- | :---: | ---: |
    | git status | git status | git status |
    | git diff | git diff | git diff |
    ```

    ```html
    <table>
      <thead>
       <tr>
        <th align="left">左对齐</th>
        <th align="center">居中对齐</th>
        <th align="right">右对齐</th>
       </tr>
      </thead>
      <tbody>
       <tr>
        <td align="left">git status</td>
        <td align="center">git status</td>
        <td align="right">git status</td>
       </tr>
       <tr>
        <td align="left">git diff</td>
        <td align="center">git diff</td>
        <td align="right">git diff</td>
       </tr>
      </tbody>
    </table>
    ```

Working with
markedJS/marked

使用
markedJS/marked

Prerequisites

前置条件

  • Node.js installed (for CLI or programmatic usage)
  • Install marked globally for CLI:
    npm install -g marked
  • Or install locally:
    npm install marked
  • 已安装Node.js(用于CLI或编程调用)
  • 全局安装marked用于CLI:
    npm install -g marked
  • 或本地安装:
    npm install marked

Quick Conversion Methods

快速转换方法

See marked.md Quick Conversion Methods
详情请查看marked.md中的快速转换方法

Step-by-Step Workflows

分步工作流

See marked.md Step-by-Step Workflows
详情请查看marked.md中的分步工作流

CLI Configuration

CLI配置

Using Config Files

使用配置文件

Create
~/.marked.json
for persistent options:
json
{
  "gfm": true,
  "breaks": true
}
Or use a custom config:
bash
marked -i input.md -o output.html -c config.json
创建
~/.marked.json
文件以保存持久化配置:
json
{
  "gfm": true,
  "breaks": true
}
或使用自定义配置文件:
bash
marked -i input.md -o output.html -c config.json

CLI Options Reference

CLI选项参考

OptionDescription
-i, --input <file>
Input Markdown file
-o, --output <file>
Output HTML file
-s, --string <string>
Parse string instead of file
-c, --config <file>
Use custom config file
--gfm
Enable GitHub Flavored Markdown
--breaks
Convert newlines to
<br>
--help
Show all options
选项描述
-i, --input <file>
输入Markdown文件
-o, --output <file>
输出HTML文件
-s, --string <string>
解析字符串而非文件
-c, --config <file>
使用自定义配置文件
--gfm
启用GitHub Flavored Markdown
--breaks
将换行符转换为
<br>
--help
显示所有选项

Security Warning

安全警告

⚠️ Marked does NOT sanitize output HTML. For untrusted input, use a sanitizer:
javascript
import { marked } from 'marked';
import DOMPurify from 'dompurify';

const unsafeHtml = marked.parse(untrustedMarkdown);
const safeHtml = DOMPurify.sanitize(unsafeHtml);
Recommended sanitizers:
⚠️ marked不会对输出的HTML进行清理。处理不可信输入时,请使用清理工具:
javascript
import { marked } from 'marked';
import DOMPurify from 'dompurify';

const unsafeHtml = marked.parse(untrustedMarkdown);
const safeHtml = DOMPurify.sanitize(unsafeHtml);
推荐的清理工具:

Supported Markdown Flavors

支持的Markdown语法

FlavorSupport
Original Markdown100%
CommonMark 0.3198%
GitHub Flavored Markdown97%
语法类型支持程度
原始Markdown100%
CommonMark 0.3198%
GitHub Flavored Markdown97%

Troubleshooting

常见问题排查

IssueSolution
Special characters at file startStrip zero-width chars:
content.replace(/^[\u200B\u200C\u200D\uFEFF]/,"")
Code blocks not highlightingAdd a syntax highlighter like highlight.js
Tables not renderingEnsure
gfm: true
option is set
Line breaks ignoredSet
breaks: true
in options
XSS vulnerability concernsUse DOMPurify to sanitize output
问题解决方案
文件开头存在特殊字符移除零宽字符:
content.replace(/^[\u200B\u200C\u200D\uFEFF]/,"")
代码块未高亮添加语法高亮工具如highlight.js
表格未渲染确保已设置
gfm: true
选项
换行符被忽略在配置中设置
breaks: true
存在XSS漏洞风险使用DOMPurify清理输出内容

Working with
pandoc

使用
pandoc

Prerequisites

前置条件

  • Pandoc installed (download from https://pandoc.org/installing.html)
  • For PDF output: LaTeX installation (MacTeX on macOS, MiKTeX on Windows, texlive on Linux)
  • Terminal/command prompt access
  • 已安装Pandoc(从https://pandoc.org/installing.html下载)
  • 若需生成PDF:需安装LaTeX(macOS使用MacTeX,Windows使用MiKTeX,Linux使用texlive)
  • 可访问终端/命令提示符

Quick Conversion Methods

快速转换方法

Method 1: CLI Basic Conversion

方法1:CLI基础转换

bash
undefined
bash
undefined

Convert markdown to HTML

将Markdown转换为HTML

pandoc input.md -o output.html
pandoc input.md -o output.html

Convert with standalone document (includes header/footer)

转换为独立文档(包含页眉/页脚)

pandoc input.md -s -o output.html
pandoc input.md -s -o output.html

Explicit format specification

明确指定格式

pandoc input.md -f markdown -t html -s -o output.html
undefined
pandoc input.md -f markdown -t html -s -o output.html
undefined

Method 2: Filter Mode (Interactive)

方法2:过滤模式(交互式)

bash
undefined
bash
undefined

Start pandoc as a filter

启动pandoc过滤模式

pandoc
pandoc

Type markdown, then Ctrl-D (Linux/macOS) or Ctrl-Z+Enter (Windows)

输入Markdown内容,然后按Ctrl-D(Linux/macOS)或Ctrl-Z+Enter(Windows)

Hello pandoc!
Hello pandoc!

Output: <p>Hello <em>pandoc</em>!</p>

输出:<p>Hello <em>pandoc</em>!</p>

undefined
undefined

Method 3: Format Conversion

方法3:多格式转换

bash
undefined
bash
undefined

HTML to Markdown

HTML转Markdown

pandoc -f html -t markdown input.html -o output.md
pandoc -f html -t markdown input.html -o output.md

Markdown to LaTeX

Markdown转LaTeX

pandoc input.md -s -o output.tex
pandoc input.md -s -o output.tex

Markdown to PDF (requires LaTeX)

Markdown转PDF(需安装LaTeX)

pandoc input.md -s -o output.pdf
pandoc input.md -s -o output.pdf

Markdown to Word

Markdown转Word

pandoc input.md -s -o output.docx
undefined
pandoc input.md -s -o output.docx
undefined

CLI Configuration

CLI配置

OptionDescription
-f, --from <format>
Input format (markdown, html, latex, etc.)
-t, --to <format>
Output format (html, latex, pdf, docx, etc.)
-s, --standalone
Produce standalone document with header/footer
-o, --output <file>
Output file (inferred from extension)
--mathml
Convert TeX math to MathML
--metadata title="Title"
Set document metadata
--toc
Include table of contents
--template <file>
Use custom template
--help
Show all options
选项描述
-f, --from <format>
输入格式(markdown、html、latex等)
-t, --to <format>
输出格式(html、latex、pdf、docx等)
-s, --standalone
生成包含页眉/页脚的独立文档
-o, --output <file>
输出文件(格式由扩展名推断)
--mathml
将TeX数学公式转换为MathML
--metadata title="Title"
设置文档元数据
--toc
包含目录
--template <file>
使用自定义模板
--help
显示所有选项

Security Warning

安全警告

⚠️ Pandoc processes input faithfully. When converting untrusted markdown:
  • Use
    --sandbox
    mode to disable external file access
  • Validate input before processing
  • Sanitize HTML output if displayed in browsers
bash
undefined
⚠️ Pandoc会忠实地处理输入内容。转换不可信的Markdown时:
  • 使用
    --sandbox
    模式禁用外部文件访问
  • 处理前验证输入内容
  • 若需在浏览器中显示,需清理HTML输出
bash
undefined

Run in sandbox mode for untrusted input

处理不可信输入时使用沙箱模式

pandoc --sandbox input.md -o output.html
undefined
pandoc --sandbox input.md -o output.html
undefined

Supported Markdown Flavors

支持的Markdown语法

FlavorSupport
Pandoc Markdown100% (native)
CommonMarkFull (use
-f commonmark
)
GitHub Flavored MarkdownFull (use
-f gfm
)
MultiMarkdownPartial
语法类型支持程度
Pandoc Markdown100%(原生支持)
CommonMark完全支持(使用
-f commonmark
GitHub Flavored Markdown完全支持(使用
-f gfm
MultiMarkdown部分支持

Troubleshooting

常见问题排查

IssueSolution
PDF generation failsInstall LaTeX (MacTeX, MiKTeX, or texlive)
Encoding issues on WindowsRun
chcp 65001
before using pandoc
Missing standalone headersAdd
-s
flag for complete documents
Math not renderingUse
--mathml
or
--mathjax
option
Tables not renderingEnsure proper table syntax with pipes and dashes
问题解决方案
PDF生成失败安装LaTeX(MacTeX、MiKTeX或texlive)
Windows下出现编码问题使用pandoc前执行
chcp 65001
缺少独立文档页眉添加
-s
参数生成完整文档
数学公式未渲染使用
--mathml
--mathjax
选项
表格未渲染确保表格语法正确,包含管道符和短横线

Working with
gomarkdown/markdown

使用
gomarkdown/markdown

Prerequisites

前置条件

  • Go 1.18 or higher installed
  • Install the library:
    go get github.com/gomarkdown/markdown
  • For CLI tool:
    go install github.com/gomarkdown/mdtohtml@latest
  • 已安装Go 1.18或更高版本
  • 安装库:
    go get github.com/gomarkdown/markdown
  • 若需使用CLI工具:
    go install github.com/gomarkdown/mdtohtml@latest

Quick Conversion Methods

快速转换方法

Method 1: Simple Conversion (Go)

方法1:简单转换(Go代码)

go
package main

import (
    "fmt"
    "github.com/gomarkdown/markdown"
)

func main() {
    md := []byte("# Hello World\n\nThis is **bold** text.")
    html := markdown.ToHTML(md, nil, nil)
    fmt.Println(string(html))
}
go
package main

import (
    "fmt"
    "github.com/gomarkdown/markdown"
)

func main() {
    md := []byte("# Hello World\n\nThis is **bold** text.")
    html := markdown.ToHTML(md, nil, nil)
    fmt.Println(string(html))
}

Method 2: CLI Tool

方法2:CLI工具

bash
undefined
bash
undefined

Install mdtohtml

安装mdtohtml

go install github.com/gomarkdown/mdtohtml@latest
go install github.com/gomarkdown/mdtohtml@latest

Convert file

转换文件

mdtohtml input.md output.html
mdtohtml input.md output.html

Convert file (output to stdout)

转换文件并输出到标准输出

mdtohtml input.md
undefined
mdtohtml input.md
undefined

Method 3: Custom Parser and Renderer

方法3:自定义解析器和渲染器

go
package main

import (
    "github.com/gomarkdown/markdown"
    "github.com/gomarkdown/markdown/html"
    "github.com/gomarkdown/markdown/parser"
)

func mdToHTML(md []byte) []byte {
    // Create parser with extensions
    extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
    p := parser.NewWithExtensions(extensions)
    doc := p.Parse(md)

    // Create HTML renderer with extensions
    htmlFlags := html.CommonFlags | html.HrefTargetBlank
    opts := html.RendererOptions{Flags: htmlFlags}
    renderer := html.NewRenderer(opts)

    return markdown.Render(doc, renderer)
}
go
package main

import (
    "github.com/gomarkdown/markdown"
    "github.com/gomarkdown/markdown/html"
    "github.com/gomarkdown/markdown/parser"
)

func mdToHTML(md []byte) []byte {
    // 创建带扩展的解析器
    extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
    p := parser.NewWithExtensions(extensions)
    doc := p.Parse(md)

    // 创建带扩展的HTML渲染器
    htmlFlags := html.CommonFlags | html.HrefTargetBlank
    opts := html.RendererOptions{Flags: htmlFlags}
    renderer := html.NewRenderer(opts)

    return markdown.Render(doc, renderer)
}

CLI Configuration

CLI配置

The
mdtohtml
CLI tool has minimal options:
bash
mdtohtml input-file [output-file]
For advanced configuration, use the Go library programmatically with parser and renderer options:
Parser ExtensionDescription
parser.CommonExtensions
Tables, fenced code, autolinks, strikethrough, etc.
parser.AutoHeadingIDs
Generate IDs for headings
parser.NoEmptyLineBeforeBlock
No blank line needed before blocks
parser.MathJax
MathJax support for LaTeX math
HTML FlagDescription
html.CommonFlags
Common HTML output flags
html.HrefTargetBlank
Add
target="_blank"
to links
html.CompletePage
Generate complete HTML page
html.UseXHTML
Generate XHTML output
mdtohtml
CLI工具的选项较少:
bash
mdtohtml input-file [output-file]
如需高级配置,可通过Go库以编程方式设置解析器和渲染器选项:
解析器扩展描述
parser.CommonExtensions
支持表格、围栏代码块、自动链接、删除线等
parser.AutoHeadingIDs
为标题生成ID
parser.NoEmptyLineBeforeBlock
区块前无需空行
parser.MathJax
支持MathJax渲染LaTeX数学公式
HTML渲染器标志描述
html.CommonFlags
常见HTML输出标志
html.HrefTargetBlank
为链接添加
target="_blank"
html.CompletePage
生成完整HTML页面
html.UseXHTML
生成XHTML格式输出

Security Warning

安全警告

⚠️ gomarkdown does NOT sanitize output HTML. For untrusted input, use Bluemonday:
go
import (
    "github.com/microcosm-cc/bluemonday"
    "github.com/gomarkdown/markdown"
)

maybeUnsafeHTML := markdown.ToHTML(md, nil, nil)
html := bluemonday.UGCPolicy().SanitizeBytes(maybeUnsafeHTML)
Recommended sanitizer: Bluemonday
⚠️ gomarkdown不会对输出的HTML进行清理。处理不可信输入时,请使用Bluemonday:
go
import (
    "github.com/microcosm-cc/bluemonday"
    "github.com/gomarkdown/markdown"
)

maybeUnsafeHTML := markdown.ToHTML(md, nil, nil)
html := bluemonday.UGCPolicy().SanitizeBytes(maybeUnsafeHTML)
推荐的清理工具:Bluemonday

Supported Markdown Flavors

支持的Markdown语法

FlavorSupport
Original Markdown100%
CommonMarkHigh (with extensions)
GitHub Flavored MarkdownHigh (tables, fenced code, strikethrough)
MathJax/LaTeX MathSupported via extension
MmarkSupported
语法类型支持程度
原始Markdown100%
CommonMark高度支持(需启用扩展)
GitHub Flavored Markdown高度支持(表格、围栏代码块、删除线)
MathJax/LaTeX数学公式通过扩展支持
Mmark支持

Troubleshooting

常见问题排查

IssueSolution
Windows/Mac newlines not parsedUse
parser.NormalizeNewlines(input)
Tables not renderingEnable
parser.Tables
extension
Code blocks without highlightingIntegrate with syntax highlighter like Chroma
Math not renderingEnable
parser.MathJax
extension
XSS vulnerabilitiesUse Bluemonday to sanitize output
问题解决方案
Windows/Mac换行符未被正确解析使用
parser.NormalizeNewlines(input)
表格未渲染启用
parser.Tables
扩展
代码块无高亮集成语法高亮工具如Chroma
数学公式未渲染启用
parser.MathJax
扩展
存在XSS漏洞使用Bluemonday清理输出内容

Working with
jekyll

使用
jekyll

Prerequisites

前置条件

  • Ruby version 2.7.0 or higher
  • RubyGems
  • GCC and Make (for native extensions)
  • Install Jekyll and Bundler:
    gem install jekyll bundler
  • Ruby版本2.7.0或更高
  • 已安装RubyGems
  • 已安装GCC和Make(用于原生扩展)
  • 安装Jekyll和Bundler:
    gem install jekyll bundler

Quick Conversion Methods

快速转换方法

Method 1: Create New Site

方法1:创建新站点

bash
undefined
bash
undefined

Create a new Jekyll site

创建新的Jekyll站点

jekyll new myblog
jekyll new myblog

Change to site directory

进入站点目录

cd myblog
cd myblog

Build and serve locally

构建并本地预览

bundle exec jekyll serve
bundle exec jekyll serve

在浏览器访问:http://localhost:4000

undefined
undefined

Method 2: Build Static Site

方法2:构建静态站点

bash
undefined
bash
undefined

Build site to _site directory

将站点构建到_site目录

bundle exec jekyll build
bundle exec jekyll build

Build with production environment

以生产环境构建站点

JEKYLL_ENV=production bundle exec jekyll build
undefined
JEKYLL_ENV=production bundle exec jekyll build
undefined

Method 3: Live Reload Development

方法3:实时重载开发

bash
undefined
bash
undefined

Serve with live reload

启动带实时重载的预览服务

bundle exec jekyll serve --livereload
bundle exec jekyll serve --livereload

Serve with drafts

预览包含草稿的内容

bundle exec jekyll serve --drafts
undefined
bundle exec jekyll serve --drafts
undefined

CLI Configuration

CLI配置

CommandDescription
jekyll new <path>
Create new Jekyll site
jekyll build
Build site to
_site
directory
jekyll serve
Build and serve locally
jekyll clean
Remove generated files
jekyll doctor
Check for configuration issues
Serve OptionsDescription
--livereload
Reload browser on changes
--drafts
Include draft posts
--port <port>
Set server port (default: 4000)
--host <host>
Set server host (default: localhost)
--baseurl <url>
Set base URL
命令描述
jekyll new <path>
创建新的Jekyll站点
jekyll build
将站点构建到
_site
目录
jekyll serve
构建并本地预览站点
jekyll clean
删除生成的文件
jekyll doctor
检查配置问题
预览选项描述
--livereload
文件变化时自动刷新浏览器
--drafts
包含草稿文章
--port <port>
设置服务器端口(默认:4000)
--host <host>
设置服务器主机(默认:localhost)
--baseurl <url>
设置基础URL

Security Warning

安全警告

⚠️ Jekyll security considerations:
  • Avoid using
    safe: false
    in production
  • Use
    exclude
    in
    _config.yml
    to prevent sensitive files from being published
  • Sanitize user-generated content if accepting external input
  • Keep Jekyll and plugins updated
yaml
undefined
⚠️ Jekyll安全注意事项
  • 生产环境避免设置
    safe: false
  • _config.yml
    中使用
    exclude
    配置防止敏感文件被发布
  • 若接受用户生成内容,需进行清理
  • 保持Jekyll和插件为最新版本
yaml
undefined

_config.yml security settings

_config.yml中的安全配置

exclude:
  • Gemfile
  • Gemfile.lock
  • node_modules
  • vendor
undefined
exclude:
  • Gemfile
  • Gemfile.lock
  • node_modules
  • vendor
undefined

Supported Markdown Flavors

支持的Markdown语法

FlavorSupport
Kramdown (default)100%
CommonMarkVia plugin (jekyll-commonmark)
GitHub Flavored MarkdownVia plugin (jekyll-commonmark-ghpages)
RedCarpetVia plugin (deprecated)
Configure markdown processor in
_config.yml
:
yaml
markdown: kramdown
kramdown:
  input: GFM
  syntax_highlighter: rouge
语法类型支持程度
Kramdown(默认)100%
CommonMark通过插件支持(jekyll-commonmark)
GitHub Flavored Markdown通过插件支持(jekyll-commonmark-ghpages)
RedCarpet通过插件支持(已废弃)
_config.yml
中配置Markdown处理器:
yaml
markdown: kramdown
kramdown:
  input: GFM
  syntax_highlighter: rouge

Troubleshooting

常见问题排查

IssueSolution
Ruby 3.0+ fails to serveRun
bundle add webrick
Gem dependency errorsRun
bundle install
Slow buildsUse
--incremental
flag
Liquid syntax errorsCheck for unescaped
{
in content
Plugin not loadingAdd to
_config.yml
plugins list
问题解决方案
Ruby 3.0+版本下预览失败执行
bundle add webrick
Gem依赖错误执行
bundle install
构建速度慢使用
--incremental
参数
Liquid语法错误检查内容中未转义的
{
插件未加载
_config.yml
的plugins列表中添加插件

Working with
hugo

使用
hugo

Prerequisites

前置条件

Quick Conversion Methods

快速转换方法

Method 1: Create New Site

方法1:创建新站点

bash
undefined
bash
undefined

Create a new Hugo site

创建新的Hugo站点

hugo new site mysite
hugo new site mysite

Change to site directory

进入站点目录

cd mysite
cd mysite

Add a theme

添加主题

git init git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke themes/ananke echo "theme = 'ananke'" >> hugo.toml
git init git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke themes/ananke echo "theme = 'ananke'" >> hugo.toml

Create content

创建内容

hugo new content posts/my-first-post.md
hugo new content posts/my-first-post.md

Start development server

启动开发服务器

hugo server -D
undefined
hugo server -D
undefined

Method 2: Build Static Site

方法2:构建静态站点

bash
undefined
bash
undefined

Build site to public directory

将站点构建到public目录

hugo
hugo

Build with minification

构建并压缩输出内容

hugo --minify
hugo --minify

Build for specific environment

为特定环境构建站点

hugo --environment production
undefined
hugo --environment production
undefined

Method 3: Development Server

方法3:开发服务器配置

bash
undefined
bash
undefined

Start server with drafts

启动包含草稿的开发服务器

hugo server -D
hugo server -D

Start with live reload and bind to all interfaces

启动实时重载服务并绑定到所有接口

hugo server --bind 0.0.0.0 --baseURL http://localhost:1313/
hugo server --bind 0.0.0.0 --baseURL http://localhost:1313/

Start with specific port

使用指定端口启动服务

hugo server --port 8080
undefined
hugo server --port 8080
undefined

CLI Configuration

CLI配置

CommandDescription
hugo new site <name>
Create new Hugo site
hugo new content <path>
Create new content file
hugo
Build site to
public
directory
hugo server
Start development server
hugo mod init
Initialize Hugo Modules
Build OptionsDescription
-D, --buildDrafts
Include draft content
-E, --buildExpired
Include expired content
-F, --buildFuture
Include future-dated content
--minify
Minify output
--gc
Run garbage collection after build
-d, --destination <path>
Output directory
Server OptionsDescription
--bind <ip>
Interface to bind to
-p, --port <port>
Port number (default: 1313)
--liveReloadPort <port>
Live reload port
--disableLiveReload
Disable live reload
--navigateToChanged
Navigate to changed content
命令描述
hugo new site <name>
创建新的Hugo站点
hugo new content <path>
创建新的内容文件
hugo
将站点构建到
public
目录
hugo server
启动开发服务器
hugo mod init
初始化Hugo Modules
构建选项描述
-D, --buildDrafts
包含草稿内容
-E, --buildExpired
包含过期内容
-F, --buildFuture
包含未来日期的内容
--minify
压缩输出内容
--gc
构建后执行垃圾回收
-d, --destination <path>
指定输出目录
服务器选项描述
--bind <ip>
绑定到指定IP地址
-p, --port <port>
设置服务器端口(默认:1313)
--liveReloadPort <port>
设置实时重载端口
--disableLiveReload
禁用实时重载
--navigateToChanged
内容变化时自动导航到对应页面

Security Warning

安全警告

⚠️ Hugo security considerations:
  • Configure security policy in
    hugo.toml
    for external commands
  • Use
    --enableGitInfo
    carefully with public repositories
  • Validate shortcode parameters for user-generated content
toml
undefined
⚠️ Hugo安全注意事项
  • hugo.toml
    中配置外部命令的安全策略
  • 公共仓库中谨慎使用
    --enableGitInfo
  • 验证用户生成内容的短代码参数
toml
undefined

hugo.toml security settings

hugo.toml中的安全配置

[security] enableInlineShortcodes = false [security.exec] allow = ['^go$', '^npx$', '^postcss$'] [security.funcs] getenv = ['^HUGO_', '^CI$'] [security.http] methods = ['(?i)GET|POST'] urls = ['.*']
undefined
[security] enableInlineShortcodes = false [security.exec] allow = ['^go$', '^npx$', '^postcss$'] [security.funcs] getenv = ['^HUGO_', '^CI$'] [security.http] methods = ['(?i)GET|POST'] urls = ['.*']
undefined

Supported Markdown Flavors

支持的Markdown语法

FlavorSupport
Goldmark (default)100% (CommonMark compliant)
GitHub Flavored MarkdownFull (tables, strikethrough, autolinks)
CommonMark100%
Blackfriday (legacy)Deprecated, not recommended
Configure markdown in
hugo.toml
:
toml
[markup]
  [markup.goldmark]
    [markup.goldmark.extensions]
      definitionList = true
      footnote = true
      linkify = true
      strikethrough = true
      table = true
      taskList = true
    [markup.goldmark.renderer]
      unsafe = false  # Set true to allow raw HTML
语法类型支持程度
Goldmark(默认)100%(兼容CommonMark)
GitHub Flavored Markdown完全支持(表格、删除线、自动链接)
CommonMark100%
Blackfriday(旧版)已废弃,不推荐使用
hugo.toml
中配置Markdown:
toml
[markup]
  [markup.goldmark]
    [markup.goldmark.extensions]
      definitionList = true
      footnote = true
      linkify = true
      strikethrough = true
      table = true
      taskList = true
    [markup.goldmark.renderer]
      unsafe = false  # 设置为true以允许原始HTML

Troubleshooting

常见问题排查

IssueSolution
"Page not found" on pathsCheck
baseURL
in config
Theme not loadingVerify theme in
themes/
or Hugo Modules
Slow buildsUse
--templateMetrics
to identify bottlenecks
Raw HTML not renderingSet
unsafe = true
in goldmark config
Images not loadingCheck
static/
folder structure
Module errorsRun
hugo mod tidy
问题解决方案
路径访问出现“页面未找到”检查配置中的
baseURL
主题未加载验证主题是否在
themes/
目录或Hugo Modules中
构建速度慢使用
--templateMetrics
识别性能瓶颈
原始HTML未渲染在goldmark配置中设置
unsafe = true
图片无法加载检查
static/
目录结构
模块错误执行
hugo mod tidy

References

参考资料

Writing and Styling Markdown

Markdown编写与样式

markedJS/marked

markedJS/marked

pandoc

pandoc

gomarkdown/markdown

gomarkdown/markdown

jekyll

jekyll

hugo

hugo