From b41d9bff51bb12e05e89ca893b4005abaecbf2c9 Mon Sep 17 00:00:00 2001 From: Joe Cheng Date: Wed, 18 Jul 2012 14:44:44 -0700 Subject: [PATCH] HTML escaping utility function --- R/ui.R | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/R/ui.R b/R/ui.R index 4da72cf11..5d3ffb97e 100644 --- a/R/ui.R +++ b/R/ui.R @@ -80,6 +80,45 @@ style <- function(...) { tag("style", ...) } +htmlEscape <- local({ + .htmlSpecials <- list( + `&` = '&', + `<` = '<', + `>` = '>' + ) + .htmlSpecialsPattern <- paste(names(.htmlSpecials), collapse='|') + .htmlSpecialsAttrib <- c( + .htmlSpecials, + `'` = ''', + `"` = '"', + `\r` = ' ', + `\n` = ' ' + ) + .htmlSpecialsPatternAttrib <- paste(names(.htmlSpecialsAttrib), collapse='|') + + function(text, attribute=T) { + pattern <- if(attribute) + .htmlSpecialsPatternAttrib + else + .htmlSpecialsPattern + + # Short circuit in the common case that there's nothing to escape + if (!grep(pattern, text)) + return(text) + + specials <- if(attribute) + .htmlSpecialsAttrib + else + .htmlSpecials + + for (chr in names(specials)) { + text <- gsub(chr, specials[[chr]], text, fixed=T) + } + + return(text) + } +}) + shinyPlot <- function(outputId) { list(head(script(src="foobar.js"), style(src="foobar.css")),