闪亮 - 在数据表中显示URL

时间:2017-06-15 15:07:38

标签: r shiny dt

我有一个DT包中的数据表,其中包含多个列,其中一列包含URL。有没有办法可以让这些网址显示为用户可以在Shiny应用内点击的超链接?另外,如果URL非常长(如第4个随机谷歌搜索),那么只显示前25个字符而不会破坏超链接的功能吗?

下面是一些示例代码。

require(DT)
require(shiny)

web_names <- c("google", "yahoo", "Stack Overflow", "Random Google Search")
url <- c( "https://www.google.com/", "https://www.yahoo.com/", "https://stackoverflow.com/", "https://www.google.com/search?q=random+google+search&oq=random+google+search&aqs=chrome..69i57j0l5.3264j0j7&sourceid=chrome&ie=UTF-8")
websites <- data.frame(web_names, url)

ui <- fluidPage(
  DT::dataTableOutput("websitesTable")
)


server<-function(input,output,session) {
output$websitesTable <- DT::renderDataTable({datatable({websites})})
}

shinyApp(ui=ui, server=server)

更新:根据Ryan Morton的建议帖子,我尝试调整代码。我的问题是现在用户创建的createLink函数中包含的sprintf函数。出现链接按钮,但未到达所需位置。

#app.R#

library(shiny)

web_names <- c("google", "yahoo", "Stack Overflow", "Random Google Search")
url <- c( "https://www.google.com/", "https://www.yahoo.com/", "https://stackoverflow.com/", "https://www.google.com/search?q=random+google+search&oq=random+google+search&aqs=chrome..69i57j0l5.3264j0j7&sourceid=chrome&ie=UTF-8")
websites <- data.frame(web_names, url)
createLink <- function(val) {
  sprintf('<a href="" target="_blank" class="btn btn-primary">Info</a>', val)
}

websites$url_link <- createLink(websites$url)

ui <- fluidPage(  
  titlePanel("Table with Links!"),
  sidebarLayout(
    sidebarPanel(
      h4("Click the link in the table to go to the url listed.")
    ),
    mainPanel(
      dataTableOutput('table1')
    )
  )
)

server <- function(input, output) {

  output$table1 <- renderDataTable({ datatable({websites})
    return(websites)

  }, escape = FALSE)
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

稍微调整提供的代码,它应该产生所需的输出:

createLink <- function(val) {
  sprintf(paste0('<a href="', URLdecode(val),'" target="_blank">', substr(val, 1, 25) ,'</a>'))
}
websites$url <- createLink(websites$url)

HTML的工作原理如下:<a href="LINK", otherOptions,...> Linktext </a> 因此,您可以将链接与paste0()substr()粘贴在一起。

相关问题