DEV Community

BC
BC

Posted on

Day28:convert markdown to html - 100DayOfRust

We can use comrak crate to convert Markdown to HTML code:

In Cargo.toml:

[dependencies]
comrak = "0.6.2"
Enter fullscreen mode Exit fullscreen mode

In main.rs:

use comrak::{markdown_to_html, ComrakOptions};


fn main() {
    let md_content = r#"
## Rust Introduction

Rust is a programming language.

### Hello World

'''rust
fn main() {
    println!("Hello, world!");
}
'''

### Reference
Rust official website: www.rust-lang.org

    "#;

    let option = ComrakOptions::default();
    let rendered = markdown_to_html(md_content, &option);
    println!("{}", rendered);

    println!("{}", "-".repeat(20));

    // add ext_autolink option, link will be auto wrapped by a tag
    let option = ComrakOptions {
        ext_autolink: true,
        ..ComrakOptions::default()
    };
    let rendered = markdown_to_html(md_content, &option);
    println!("{}", rendered);
}

Enter fullscreen mode Exit fullscreen mode

Run code cargo run:

<h2>Rust Introduction</h2>
<p>Rust is a programming language.</p>
<h3>Hello World</h3>
<pre><code class="language-rust">fn main() {
    println!(&quot;Hello, world!&quot;);
}

</code></pre>
<h3>Reference</h3>
<p>Rust official website: www.rust-lang.org</p>

--------------------
<h2>Rust Introduction</h2>
<p>Rust is a programming language.</p>
<h3>Hello World</h3>
<pre><code class="language-rust">fn main() {
    println!(&quot;Hello, world!&quot;);
}

</code></pre>
<h3>Reference</h3>
<p>Rust official website: <a href="http://www.rust-lang.org">www.rust-lang.org</a></p>

Enter fullscreen mode Exit fullscreen mode

You can see with the option ext_autolink: true, url will be auto wrapped by <a> tag. For more conversion options, check here.

Reference

Top comments (0)