tera_v1/
utils.rs

1use v_htmlescape::escape;
2/// Escape HTML following [OWASP](https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet)
3///
4/// Escape the following characters with HTML entity encoding to prevent switching
5/// into any execution context, such as script, style, or event handlers. Using
6/// hex entities is recommended in the spec. In addition to the 5 characters
7/// significant in XML (&, <, >, ", '), the forward slash is included as it helps
8/// to end an HTML entity.
9///
10/// ```text
11/// & --> &amp;
12/// < --> &lt;
13/// > --> &gt;
14/// " --> &quot;
15/// ' --> &#x27;     &apos; is not recommended
16/// / --> &#x2F;     forward slash is included as it helps end an HTML entity
17/// ```
18#[inline]
19pub fn escape_html(input: &str) -> String {
20    escape(input).to_string()
21}
22
23#[cfg(test)]
24mod tests {
25    use super::escape_html;
26
27    #[test]
28    fn test_escape_html() {
29        let tests = vec![
30            (r"", ""),
31            (r"a&b", "a&amp;b"),
32            (r"<a", "&lt;a"),
33            (r">a", "&gt;a"),
34            (r#"""#, "&quot;"),
35            (r#"'"#, "&#x27;"),
36            (r#"大阪"#, "大阪"),
37        ];
38        for (input, expected) in tests {
39            assert_eq!(escape_html(input), expected);
40        }
41        let empty = String::new();
42        assert_eq!(escape_html(&empty), empty);
43    }
44}