简体   繁体   中英

Function to preview a chunk of html in the RStudio viewer pane

I'd like to preview/render a generated piece of html in the rstudio viewer pane, without having to knit the entire rmarkdown document

For example:

preview_html(mtcars %>% kable(format = "html"))

generates a block of HTML. I'd like it to be rendered in the preview pane.

The following function writes a temporary html file with just the code chunk, and opens it in the viewer:

preview_html <- function(code){
  tempDir <- tempfile()
  dir.create(tempDir)
  htmlFile <- file.path(tempDir, "index.html")
  writeLines(paste0('<html><body>',
                    code,
                    '</body></html>'), htmlFile)
  viewer <- getOption("viewer")
  viewer(htmlFile)
}

preview_html(mtcars %>% kable(format = "html")) # Opens in viewer pane

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM