Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Sanitize HTML With Ammonia In Rust

Overview

I'm using the ammonia rust crate to sanitize HTML for my twitch bot. I'm using it like this :

use ammonia::Builder;
use maplit::{hashmap, hashset};

fn main() {
    let source = r#"
        <div>
            <span id="alfa" class="bravo">charlie</span>
        </div>
    "#;
    let scrubbed = sanatize_html(source);
    dbg!(scrubbed);
}

fn sanatize_html(source: &str) -> String {
    let tags = hashset!["span"];
    let tag_attrs = hashmap![
        "span" => hashset!["id"]
    ];
    Builder::new()
        .tags(tags)
        .tag_attributes(tag_attrs)
        .clean(source)
        .to_string()
}

Details

Installation

Installing the crate is done with :

cargo add ammonia
cargo add maplit

The matlit crate provides the macros used in the example to make the hashsets and hashmap. It's not required. Using the std hash features works as well.

Footnotes And References