Skip to main content

forge/
escape.rs

1//! Escape primitives. Askama already escapes `{{ }}` by default; `{!! !!}` opts out via `|safe`.
2
3/// HTML-escape a string. (Convenience — Askama uses its own escaper by default.)
4pub fn html(input: &str) -> String {
5    let mut out = String::with_capacity(input.len());
6    for ch in input.chars() {
7        match ch {
8            '&' => out.push_str("&"),
9            '<' => out.push_str("&lt;"),
10            '>' => out.push_str("&gt;"),
11            '"' => out.push_str("&quot;"),
12            '\'' => out.push_str("&#x27;"),
13            other => out.push(other),
14        }
15    }
16    out
17}
18
19/// Mark a string as safe — Askama receives this through `|safe` to opt out of escaping.
20pub fn safe(input: impl Into<String>) -> SafeString {
21    SafeString(input.into())
22}
23
24#[derive(Debug, Clone)]
25pub struct SafeString(pub String);
26
27impl std::fmt::Display for SafeString {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.write_str(&self.0)
30    }
31}