pulldown_cmark::html

Function push_html

source
pub fn push_html<'a, I>(s: &mut String, iter: I)
where I: Iterator<Item = Event<'a>>,
Expand description

Iterate over an Iterator of Events, generate HTML for each Event, and push it to a String.

ยงExamples

use pulldown_cmark::{html, Parser};

let markdown_str = r#"
hello
=====

* alpha
* beta
"#;
let parser = Parser::new(markdown_str);

let mut html_buf = String::new();
html::push_html(&mut html_buf, parser);

assert_eq!(html_buf, r#"<h1>hello</h1>
<ul>
<li>alpha</li>
<li>beta</li>
</ul>
"#);
Examples found in repository?
examples/string-to-string.rs (line 15)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn main() {
    let markdown_input: &str = "Hello world, this is a ~~complicated~~ *very simple* example.";
    println!("Parsing the following markdown string:\n{}", markdown_input);

    // Set up options and parser. Strikethroughs are not part of the CommonMark standard
    // and we therefore must enable it explicitly.
    let mut options = Options::empty();
    options.insert(Options::ENABLE_STRIKETHROUGH);
    let parser = Parser::new_ext(markdown_input, options);

    // Write to String buffer.
    let mut html_output: String = String::with_capacity(markdown_input.len() * 3 / 2);
    html::push_html(&mut html_output, parser);

    // Check that the output is what we expected.
    let expected_html: &str =
        "<p>Hello world, this is a <del>complicated</del> <em>very simple</em> example.</p>\n";
    assert_eq!(expected_html, &html_output);

    // Write result to stdout.
    println!("\nHTML output:\n{}", &html_output);
}
More examples
Hide additional examples
examples/broken-link-callbacks.rs (line 26)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
fn main() {
    let input: &str = "Hello world, check out [my website][].";
    println!("Parsing the following markdown string:\n{}", input);

    // Setup callback that sets the URL and title when it encounters
    // a reference to our home page.
    let callback = |broken_link: BrokenLink| {
        if broken_link.reference.as_ref() == "my website" {
            println!(
                "Replacing the markdown `{}` of type {:?} with a working link",
                &input[broken_link.span], broken_link.link_type,
            );
            Some(("http://example.com".into(), "my example website".into()))
        } else {
            None
        }
    };

    // Create a parser with our callback function for broken links.
    let parser = Parser::new_with_broken_link_callback(input, Options::empty(), Some(callback));

    // Write to String buffer.
    let mut html_output: String = String::with_capacity(input.len() * 3 / 2);
    html::push_html(&mut html_output, parser);

    // Check that the output is what we expected.
    let expected_html: &str =
        "<p>Hello world, check out <a href=\"http://example.com\" title=\"my example website\">my website</a>.</p>\n";
    assert_eq!(expected_html, &html_output);

    // Write result to stdout.
    println!("\nHTML output:\n{}", &html_output);
}
examples/parser-map-event-print.rs (line 34)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
fn main() {
    let markdown_input = "# Example Heading\nExample paragraph with **lorem** _ipsum_ text.";
    println!(
        "\nParsing the following markdown string:\n{}\n",
        markdown_input
    );

    // Set up the parser. We can treat is as any other iterator.
    // For each event, we print its details, such as the tag or string.
    // This filter simply returns the same event without any changes;
    // you can compare the `event-filter` example which alters the output.
    let parser = Parser::new(markdown_input).map(|event| {
        match &event {
            Event::Start(tag) => println!("Start: {:?}", tag),
            Event::End(tag) => println!("End: {:?}", tag),
            Event::Html(s) => println!("Html: {:?}", s),
            Event::InlineHtml(s) => println!("InlineHtml: {:?}", s),
            Event::Text(s) => println!("Text: {:?}", s),
            Event::Code(s) => println!("Code: {:?}", s),
            Event::DisplayMath(s) => println!("DisplayMath: {:?}", s),
            Event::InlineMath(s) => println!("Math: {:?}", s),
            Event::FootnoteReference(s) => println!("FootnoteReference: {:?}", s),
            Event::TaskListMarker(b) => println!("TaskListMarker: {:?}", b),
            Event::SoftBreak => println!("SoftBreak"),
            Event::HardBreak => println!("HardBreak"),
            Event::Rule => println!("Rule"),
        };
        event
    });

    let mut html_output = String::new();
    html::push_html(&mut html_output, parser);
    println!("\nHTML output:\n{}\n", &html_output);
}
examples/parser-map-tag-print.rs (line 108)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
fn main() {
    let markdown_input = concat!(
        "# My Heading\n",
        "\n",
        "My paragraph.\n",
        "\n",
        "* a\n",
        "* b\n",
        "* c\n",
        "\n",
        "1. d\n",
        "2. e\n",
        "3. f\n",
        "\n",
        "> my block quote\n",
        "\n",
        "```\n",
        "my code block\n",
        "```\n",
        "\n",
        "*emphasis*\n",
        "**strong**\n",
        "~~strikethrough~~\n",
        "[My Link](http://example.com)\n",
        "![My Image](http://example.com/image.jpg)\n",
        "\n",
        "| a | b |\n",
        "| - | - |\n",
        "| c | d |\n",
        "\n",
        "hello[^1]\n",
        "[^1]: my footnote\n",
    );
    println!(
        "\nParsing the following markdown string:\n{}\n",
        markdown_input
    );

    // Set up the parser. We can treat is as any other iterator.
    // For each event, we print its details, such as the tag or string.
    // This filter simply returns the same event without any changes;
    // you can compare the `event-filter` example which alters the output.
    let parser = Parser::new_ext(markdown_input, Options::all()).map(|event| {
        match &event {
            Event::Start(tag) => match tag {
                Tag::HtmlBlock => println!("HtmlBlock"),
                Tag::Heading {
                    level,
                    id,
                    classes,
                    attrs,
                } => println!(
                    "Heading heading_level: {} fragment identifier: {:?} classes: {:?} attrs: {:?}",
                    level, id, classes, attrs
                ),
                Tag::Paragraph => println!("Paragraph"),
                Tag::List(ordered_list_first_item_number) => println!(
                    "List ordered_list_first_item_number: {:?}",
                    ordered_list_first_item_number
                ),
                Tag::DefinitionList => println!("Definition list"),
                Tag::DefinitionListTitle => println!("Definition title (definition list item)"),
                Tag::DefinitionListDefinition => println!("Definition (definition list item)"),
                Tag::Item => println!("Item (this is a list item)"),
                Tag::Emphasis => println!("Emphasis (this is a span tag)"),
                Tag::Strong => println!("Strong (this is a span tag)"),
                Tag::Strikethrough => println!("Strikethrough (this is a span tag)"),
                Tag::BlockQuote(kind) => println!("BlockQuote ({:?})", kind),
                Tag::CodeBlock(code_block_kind) => {
                    println!("CodeBlock code_block_kind: {:?}", code_block_kind)
                }
                Tag::Link {
                    link_type,
                    dest_url,
                    title,
                    id,
                } => println!(
                    "Link link_type: {:?} url: {} title: {} id: {}",
                    link_type, dest_url, title, id
                ),
                Tag::Image {
                    link_type,
                    dest_url,
                    title,
                    id,
                } => println!(
                    "Image link_type: {:?} url: {} title: {} id: {}",
                    link_type, dest_url, title, id
                ),
                Tag::Table(column_text_alignment_list) => println!(
                    "Table column_text_alignment_list: {:?}",
                    column_text_alignment_list
                ),
                Tag::TableHead => println!("TableHead (contains TableRow tags"),
                Tag::TableRow => println!("TableRow (contains TableCell tags)"),
                Tag::TableCell => println!("TableCell (contains inline tags)"),
                Tag::FootnoteDefinition(label) => println!("FootnoteDefinition label: {}", label),
                Tag::MetadataBlock(kind) => println!("MetadataBlock: {:?}", kind),
            },
            _ => (),
        };
        event
    });

    let mut html_output = String::new();
    pulldown_cmark::html::push_html(&mut html_output, parser);
    println!("\nHTML output:\n{}\n", &html_output);
}