glacier-web 0.1.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! HTML helpers.

use std::fmt::Write;

/// Escapes text for safe inclusion in HTML content and attribute values.
pub fn escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(c),
        }
    }
    out
}

/// A hidden form field carrying the CSRF token; put it in every form that
/// posts to a route behind `Csrf`.
pub fn csrf_field(token: &str) -> String {
    let mut out = String::new();
    let _ = write!(
        out,
        r#"<input type="hidden" name="{}" value="{}">"#,
        crate::csrf::FORM_FIELD,
        escape(token)
    );
    out
}

/// A hidden `_method` field so HTML forms can send PATCH, PUT or DELETE
/// (requires the `MethodOverride` middleware).
pub fn method_field(method: &str) -> String {
    format!(
        r#"<input type="hidden" name="_method" value="{}">"#,
        escape(method)
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn escapes_special_characters() {
        assert_eq!(
            escape(r#"<a href="x">Tom & 'Jerry'</a>"#),
            "&lt;a href=&quot;x&quot;&gt;Tom &amp; &#39;Jerry&#39;&lt;/a&gt;"
        );
    }
}