Newer
Older
1
2
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
use std::fmt::{Display, Formatter};
pub struct Attribute {
key: String,
value: String,
}
impl Display for Attribute {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}=\"{}\"", self.key, self.value.replace('"', "\\\""))
}
}
impl<A, B> From<(A, B)> for Attribute
where
A: ToString,
B: ToString,
{
fn from(item: (A, B)) -> Self {
Attribute {
key: item.0.to_string(),
value: item.1.to_string(),
}
}
}
fn format_attr_list(list: &[Attribute]) -> String {
list.iter()
.map(|attr| format!("{}", attr))
.reduce(|prev, cur| format!("{} {}", prev, cur))
.unwrap_or_default()
}
fn format_child_list(list: &[String]) -> String {
list.iter()
.fold(String::new(), |prev, cur| format!("{}\n{}", prev, cur))
}
pub struct El;
impl El {
pub fn open(tag: impl ToString, attributes: &[Attribute]) -> String {
format!("<{} {}>", tag.to_string(), format_attr_list(attributes))
}
pub fn close(tag: impl ToString) -> String {
format!("</{}>", tag.to_string())
}
pub fn create(tag: impl ToString, attributes: &[Attribute]) -> String {
format!("<{} {} />", tag.to_string(), format_attr_list(attributes))
}
pub fn with_children(
tag: impl ToString,
attributes: Vec<Attribute>,
children: Vec<String>,
) -> String {
format!(
"<{tag} {attr}>{children}</{tag}>",
tag = tag.to_string(),
attr = format_attr_list(&attributes),
children = format_child_list(&children)
)
}
}