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)
3fn main() {
4    let markdown_input: &str = "Hello world, this is a ~~complicated~~ *very simple* example.";
5    println!("Parsing the following markdown string:\n{}", markdown_input);
6
7    // Set up options and parser. Strikethroughs are not part of the CommonMark standard
8    // and we therefore must enable it explicitly.
9    let mut options = Options::empty();
10    options.insert(Options::ENABLE_STRIKETHROUGH);
11    let parser = Parser::new_ext(markdown_input, options);
12
13    // Write to String buffer.
14    let mut html_output: String = String::with_capacity(markdown_input.len() * 3 / 2);
15    html::push_html(&mut html_output, parser);
16
17    // Check that the output is what we expected.
18    let expected_html: &str =
19        "<p>Hello world, this is a <del>complicated</del> <em>very simple</em> example.</p>\n";
20    assert_eq!(expected_html, &html_output);
21
22    // Write result to stdout.
23    println!("\nHTML output:\n{}", &html_output);
24}
More examples
Hide additional examples
examples/broken-link-callbacks.rs (line 26)
3fn main() {
4    let input: &str = "Hello world, check out [my website][].";
5    println!("Parsing the following markdown string:\n{}", input);
6
7    // Setup callback that sets the URL and title when it encounters
8    // a reference to our home page.
9    let callback = |broken_link: BrokenLink| {
10        if broken_link.reference.as_ref() == "my website" {
11            println!(
12                "Replacing the markdown `{}` of type {:?} with a working link",
13                &input[broken_link.span], broken_link.link_type,
14            );
15            Some(("http://example.com".into(), "my example website".into()))
16        } else {
17            None
18        }
19    };
20
21    // Create a parser with our callback function for broken links.
22    let parser = Parser::new_with_broken_link_callback(input, Options::empty(), Some(callback));
23
24    // Write to String buffer.
25    let mut html_output: String = String::with_capacity(input.len() * 3 / 2);
26    html::push_html(&mut html_output, parser);
27
28    // Check that the output is what we expected.
29    let expected_html: &str =
30        "<p>Hello world, check out <a href=\"http://example.com\" title=\"my example website\">my website</a>.</p>\n";
31    assert_eq!(expected_html, &html_output);
32
33    // Write result to stdout.
34    println!("\nHTML output:\n{}", &html_output);
35}
examples/parser-map-event-print.rs (line 34)
3fn main() {
4    let markdown_input = "# Example Heading\nExample paragraph with **lorem** _ipsum_ text.";
5    println!(
6        "\nParsing the following markdown string:\n{}\n",
7        markdown_input
8    );
9
10    // Set up the parser. We can treat is as any other iterator.
11    // For each event, we print its details, such as the tag or string.
12    // This filter simply returns the same event without any changes;
13    // you can compare the `event-filter` example which alters the output.
14    let parser = Parser::new(markdown_input).map(|event| {
15        match &event {
16            Event::Start(tag) => println!("Start: {:?}", tag),
17            Event::End(tag) => println!("End: {:?}", tag),
18            Event::Html(s) => println!("Html: {:?}", s),
19            Event::InlineHtml(s) => println!("InlineHtml: {:?}", s),
20            Event::Text(s) => println!("Text: {:?}", s),
21            Event::Code(s) => println!("Code: {:?}", s),
22            Event::DisplayMath(s) => println!("DisplayMath: {:?}", s),
23            Event::InlineMath(s) => println!("Math: {:?}", s),
24            Event::FootnoteReference(s) => println!("FootnoteReference: {:?}", s),
25            Event::TaskListMarker(b) => println!("TaskListMarker: {:?}", b),
26            Event::SoftBreak => println!("SoftBreak"),
27            Event::HardBreak => println!("HardBreak"),
28            Event::Rule => println!("Rule"),
29        };
30        event
31    });
32
33    let mut html_output = String::new();
34    html::push_html(&mut html_output, parser);
35    println!("\nHTML output:\n{}\n", &html_output);
36}
examples/parser-map-tag-print.rs (line 110)
3fn main() {
4    let markdown_input = concat!(
5        "# My Heading\n",
6        "\n",
7        "My paragraph.\n",
8        "\n",
9        "* a\n",
10        "* b\n",
11        "* c\n",
12        "\n",
13        "1. d\n",
14        "2. e\n",
15        "3. f\n",
16        "\n",
17        "> my block quote\n",
18        "\n",
19        "```\n",
20        "my code block\n",
21        "```\n",
22        "\n",
23        "*emphasis*\n",
24        "**strong**\n",
25        "~~strikethrough~~\n",
26        "[My Link](http://example.com)\n",
27        "![My Image](http://example.com/image.jpg)\n",
28        "\n",
29        "| a | b |\n",
30        "| - | - |\n",
31        "| c | d |\n",
32        "\n",
33        "hello[^1]\n",
34        "[^1]: my footnote\n",
35    );
36    println!(
37        "\nParsing the following markdown string:\n{}\n",
38        markdown_input
39    );
40
41    // Set up the parser. We can treat is as any other iterator.
42    // For each event, we print its details, such as the tag or string.
43    // This filter simply returns the same event without any changes;
44    // you can compare the `event-filter` example which alters the output.
45    let parser = Parser::new_ext(markdown_input, Options::all()).map(|event| {
46        match &event {
47            Event::Start(tag) => match tag {
48                Tag::HtmlBlock => println!("HtmlBlock"),
49                Tag::Heading {
50                    level,
51                    id,
52                    classes,
53                    attrs,
54                } => println!(
55                    "Heading heading_level: {} fragment identifier: {:?} classes: {:?} attrs: {:?}",
56                    level, id, classes, attrs
57                ),
58                Tag::Paragraph => println!("Paragraph"),
59                Tag::List(ordered_list_first_item_number) => println!(
60                    "List ordered_list_first_item_number: {:?}",
61                    ordered_list_first_item_number
62                ),
63                Tag::DefinitionList => println!("Definition list"),
64                Tag::DefinitionListTitle => println!("Definition title (definition list item)"),
65                Tag::DefinitionListDefinition => println!("Definition (definition list item)"),
66                Tag::Item => println!("Item (this is a list item)"),
67                Tag::Emphasis => println!("Emphasis (this is a span tag)"),
68                Tag::Superscript => println!("Superscript (this is a span tag)"),
69                Tag::Subscript => println!("Subscript (this is a span tag)"),
70                Tag::Strong => println!("Strong (this is a span tag)"),
71                Tag::Strikethrough => println!("Strikethrough (this is a span tag)"),
72                Tag::BlockQuote(kind) => println!("BlockQuote ({:?})", kind),
73                Tag::CodeBlock(code_block_kind) => {
74                    println!("CodeBlock code_block_kind: {:?}", code_block_kind)
75                }
76                Tag::Link {
77                    link_type,
78                    dest_url,
79                    title,
80                    id,
81                } => println!(
82                    "Link link_type: {:?} url: {} title: {} id: {}",
83                    link_type, dest_url, title, id
84                ),
85                Tag::Image {
86                    link_type,
87                    dest_url,
88                    title,
89                    id,
90                } => println!(
91                    "Image link_type: {:?} url: {} title: {} id: {}",
92                    link_type, dest_url, title, id
93                ),
94                Tag::Table(column_text_alignment_list) => println!(
95                    "Table column_text_alignment_list: {:?}",
96                    column_text_alignment_list
97                ),
98                Tag::TableHead => println!("TableHead (contains TableRow tags"),
99                Tag::TableRow => println!("TableRow (contains TableCell tags)"),
100                Tag::TableCell => println!("TableCell (contains inline tags)"),
101                Tag::FootnoteDefinition(label) => println!("FootnoteDefinition label: {}", label),
102                Tag::MetadataBlock(kind) => println!("MetadataBlock: {:?}", kind),
103            },
104            _ => (),
105        };
106        event
107    });
108
109    let mut html_output = String::new();
110    pulldown_cmark::html::push_html(&mut html_output, parser);
111    println!("\nHTML output:\n{}\n", &html_output);
112}