html_node_core/node/
text.rs

1use std::fmt::{self, Display, Formatter};
2
3/// A text node.
4///
5/// ```html
6/// <div>
7///     I'm a text node!
8/// </div>
9#[derive(Debug, Clone, PartialEq, Eq)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub struct Text {
12    /// The text of the node.
13    ///
14    /// ```html
15    /// <div>
16    ///     text
17    /// </div>
18    pub text: String,
19}
20
21impl Display for Text {
22    /// Format as HTML encoded string.
23    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
24        let encoded_value = html_escape::encode_text_minimal(&self.text);
25        write!(f, "{encoded_value}")
26    }
27}
28
29impl<T> From<T> for Text
30where
31    T: Into<String>,
32{
33    /// Create a new text element from anything that can
34    /// be converted into a string.
35    fn from(text: T) -> Self {
36        Self { text: text.into() }
37    }
38}