home ~ projects ~ socials

HTML Escaping In Rust

```cargo
[dependencies]
html-escape = "0.2.13"
```

use html_escape::*;

fn main() {
  let source = r#"_ < _ > _ " _ ' _ / _ & _"#;
  println!("encode_safe: {}", encode_safe(source));
  println!("encode_text: {}", encode_text(source));
  println!("encode_quoted_attribute: {}", encode_quoted_attribute(source));
  println!("encode_double_quoted_attribute: {}", encode_double_quoted_attribute(source));
  println!("encode_single_quoted_attribute: {}", encode_single_quoted_attribute(source));
}
Output:
encode_safe: _ &lt; _ &gt; _ &quot; _ &#x27; _ &#x2F; _ &amp; _
encode_text: _ &lt; _ &gt; _ " _ ' _ / _ &amp; _
encode_quoted_attribute: _ &lt; _ &gt; _ &quot; _ &#x27; _ / _ &amp; _
encode_double_quoted_attribute: _ &lt; _ &gt; _ &quot; _ ' _ / _ &amp; _
encode_single_quoted_attribute: _ &lt; _ &gt; _ " _ &#x27; _ / _ &amp; _

Full Escape

```cargo
[dependencies]
html-escape = "0.2.13"
```

use html_escape::*;

fn main() {
  let source = r#"_ < _ > _ " _ ' _ / _ & _"#;
  println!("encode_unquoted_attribute: {}", encode_unquoted_attribute(source));
}
Output:
encode_unquoted_attribute: &#x5F;&#x20;&lt;&#x20;&#x5F;&#x20;&gt;&#x20;&#x5F;&#x20;&quot;&#x20;&#x5F;&#x20;&#x27;&#x20;&#x5F;&#x20;&#x2F;&#x20;&#x5F;&#x20;&amp;&#x20;&#x5F;

Notes

  • This is what I'm using in Neopoligen in additon to minijinja for the individual things like inline code tokens
  • There's also escape_script and escape_style which deals with script and style tags. That's not what I'm interested in here.
-- end of line --

References