简体   繁体   English

Function 在 RStudio 查看器窗格中预览一块 html

[英]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我想在 rstudio 查看器窗格中预览/渲染生成的 html 片段,而不必编织整个 rmarkdown 文档

For example:例如:

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

generates a block of HTML.生成 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:以下 function 仅使用代码块写入临时 html 文件,并在查看器中打开它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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