html_site_generator/
attributes.rs1use std::io::Write;
2
3use anyhow::Result;
4use derive_builder::Builder;
5
6use crate::html::IntoHtmlNode;
7
8#[derive(Debug, Default, Builder)]
9pub struct HtmlAttributes {
10 #[builder(setter(strip_option, into), default)]
11 class: Option<String>,
12 #[builder(setter(strip_option, into), default)]
13 id: Option<String>,
14}
15
16pub trait SetHtmlAttributes {
17 fn get_attributes(&self) -> &HtmlAttributes;
18 fn get_attributes_mut(&mut self) -> &mut HtmlAttributes;
19
20 fn set_class<S: Into<String>>(&mut self, class: S) {
21 let attributes = self.get_attributes_mut();
22 attributes.class = Some(class.into())
23 }
24
25 fn clear_class(&mut self) {
26 let attributes = self.get_attributes_mut();
27 attributes.class = None
28 }
29
30 fn set_id<S: Into<String>>(&mut self, id: S) {
31 let attributes = self.get_attributes_mut();
32 attributes.id = Some(id.into())
33 }
34
35 fn clear_id(&mut self) {
36 let attributes = self.get_attributes_mut();
37 attributes.id = None
38 }
39}
40
41impl IntoHtmlNode for HtmlAttributes {
42 fn transform_into_html_node(&self, buffer: &mut dyn Write) -> Result<()> {
43 if let Some(class) = &self.class {
44 write!(buffer, " class=\"{}\"", class)?;
45 }
46
47 if let Some(id) = &self.id {
48 write!(buffer, " id=\"{}\"", id)?;
49 }
50
51 Ok(())
52 }
53}