Ammonia add A tag attribute


Hi there

I’m using Ammonia to clean external HTML and add target="_blank" to all A tags.

I’m working on the default settings because they suits my needs except the target attribute.

    desc = Builder::default()
    .add_tag_attributes("a", &["target"])
    .add_tag_attribute_values("a", "target", &["_blank"])

But this does nothing to the existing HTML.

My question is this, how do I add a new attribute to an existing tag?

1 Like

Hi. I’m ammonia’s #1 contributor, and that’s not what add_tag_attribute_values does:

Add additonal whitelisted tag-specific attribute values without overwriting old ones.

By referring to it as a “whitelist”, it means that the listed options are allowed and any other value will be rejected. This is a bit more obvious if you look at what it does when there’s more than one item in the supplied list:

let desc = Builder::default()
    .add_tag_attributes("a", &["target"])
    .add_tag_attribute_values("a", "target", &["_blank", "my_frame"])
    .clean(r#"<a href="" target="_blank">1</a><a href="" target="my_frame">2</a><a href="" target="banned_value">3</a>"#)
assert_eq!(&desc[..], r#"<a href="" target="_blank">1</a><a href="" target="my_frame">2</a><a href="">3</a>"#);

Ammonia doesn’t currently have an API for doing what you want (which is adding a new attribute where none previously existed). I’m cool with adding it, if you think it’d be useful (it’s really a generalization of the special support for rel).

1 Like

But of course. I lost sight of what Ammonia is; a library for cleaning HTML.

IMHO I actually think, that adding this kind of feature is out of scope of Ammonia,

Btw you’re doing a great job with Ammonia and keep on doing it.