21.3 Escaping

  • need to escape &, <, and >
  • don’t “double escape”
  • leave HTML alone

21.3.1 S3 Class

html <- function(x) structure(x, class = "advr_html")

#dispatch
print.advr_html <- function(x, ...) {
  out <- paste0("<HTML> ", x)
  cat(paste(strwrap(out), collapse = "\n"), "\n", sep = "")
}

21.3.2 Generic

escape <- function(x) UseMethod("escape")
escape.character <- function(x) {
  x <- gsub("&", "&amp;", x)
  x <- gsub("<", "&lt;", x)
  x <- gsub(">", "&gt;", x)
  html(x)
}
escape.advr_html <- function(x) x

21.3.3 Checks

escape("This is some text.")
#> <HTML> This is some text.
escape("x > 1 & y < 2")
#> <HTML> x &gt; 1 &amp; y &lt; 2
escape(escape("This is some text. 1 > 2")) #double escape
#> <HTML> This is some text. 1 &gt; 2
escape(html("<hr />")) #already html
#> <HTML> <hr />