在 Shiny 的 DataTable 中包含 link 到本地 html 文件

Include link to local html file in DataTable in Shiny

我想将 link 添加到本地 html 文件中,该文件位于我闪亮的应用程序的 www 目录中,在 data.table 的列中。单击时应打开一个新选项卡,显示 html 文件。 我找到了 link 访问互联网页面的解决方案,但我该如何调整它,以便 Shiny 在浏览器中呈现时找到本地文件?

这是我的代码

library(DT)
library(shiny)

link <- "www/my_html.html"
link <- paste0("<a href='", link,"' target='_blank'>", link,"</a>")  # works fine for global url, but not for local file
df <- data.frame(a = 10.5, b = 48, link = link)

ui <- fluidPage(
  DT::dataTableOutput('table1')
)

server <- function(input, output) {
  output$table1 <- DT::renderDataTable({df}, escape = -3)
}

shinyApp(ui, server)

或许您可以尝试 运行 您的应用使用闪亮的文件夹。确保您的 my_html.html 文件位于闪亮文件夹的 www 文件夹中。

ui.R

library(DT)
library(shiny)

fluidPage(
  DT::dataTableOutput('table1')
)

server.R

library(DT)
library(shiny)

df <- data.frame(a = 10.5, b = 48, link = "<a href='my_html.html' target='blank' >MyFile</a>")

function(input, output) {
  output$table1 <- DT::renderDataTable({df}, escape = FALSE)
}

我认为您的代码的主要问题是您将 html 文件的地址指定为 link <- "www/my_html.html"。你应该去掉 www/.

的确 在你的应用程序目录中你必须有一个 www 目录,你的 html 文件应该在这个 www 目录中。 但是要正确处理你的您应该认为您的工作目录已经在 www/ 目录中的文件。

如果您在单个 app.R 文件或 ui.R + server.R 文件的组合中拥有闪亮的应用程序,这两种方式都有效。

其他细节在renderDataTable()函数的escape参数中。它不应等于 -3,请改用:DT::renderDataTable({df}, escape = FALSE)

因此最终代码如下所示(假设您有两个 html 文件):

library(shiny)

link <- c("my_html_1.html", "my_html_2.html")
link <- sprintf('<a href="%s" target="_blank">click_here</a>', link)

df <- data.frame(name = c("1st_file", "2nd_file"), 
    value = c(10.5, 48), 
    link = link)

ui <- fluidPage(
  dataTableOutput('table1')
)

server <- function(input, output) {
  output$table1 <- renderDataTable({df}, escape = FALSE)
}

shinyApp(ui, server)