html_ast/elements/
display.rs

1use super::*;
2use std::borrow::Cow;
3
4impl Display for HtmlElement {
5    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
6        f.write_str("<")?;
7        f.write_str(&self.tag)?;
8        if !self.id.is_empty() {
9            f.write_str(" id=\"")?;
10            f.write_str(&self.id)?;
11            f.write_str("\"")?;
12        }
13        if !self.classes.is_empty() {
14            f.write_str(" class=\"")?;
15            for (i, class) in self.classes.iter().enumerate() {
16                if i > 0 {
17                    f.write_str(" ")?;
18                }
19                f.write_str(class)?;
20            }
21            f.write_str("\"")?;
22        }
23        for (key, value) in &self.attributes {
24            f.write_str(" ")?;
25            f.write_str(key)?;
26            f.write_str("=\"")?;
27            f.write_str(value)?;
28            f.write_str("\"")?;
29        }
30        if self.children.is_empty() {
31            f.write_str("/>")
32        }
33        else {
34            f.write_str(">")?;
35            for node in &self.children {
36                f.write_str(&node.to_string())?;
37            }
38            f.write_str("</")?;
39            f.write_str(&self.tag)?;
40            f.write_str(">")
41        }
42    }
43}
44
45impl From<HtmlElement> for HtmlNode {
46    fn from(value: HtmlElement) -> Self {
47        Self::Element(value)
48    }
49}
50
51impl From<String> for HtmlNode {
52    fn from(text: String) -> Self {
53        Self::Text(Cow::Owned(text))
54    }
55}
56impl From<&'static str> for HtmlNode {
57    fn from(text: &'static str) -> Self {
58        Self::Text(Cow::Borrowed(text))
59    }
60}