Drthm1456
Drthm1456

Reputation: 479

R shiny datatable with HTML Tags

I am trying to utilize html tags inside of a shiny datatable. I have a file in which a URL is created by some standard text and then is pasted together with another column to create the full URL. I just have the data and the server portion included here.

I also have built in a filter option to be able to filter on two of the columns and then output the data file at the end. I have a simple repeatable example of here what I am trying to accomplish but believe I need to add the escape=FALSE option; but I am unsure of where it should go. So currently I am getting the formatted html where I want the live html with the text showing column A

Here is a simplified version of my data and how I am trying to set it up. Thanks!

A <- c("Alpha", "Beta", "Gamma", "Delta")
B <- c("one","two","three","four")
C <- c("five","six","seven","eight")
Test_File <- as.data.frame(cbind(A,B,C))

 output$table <- DT::renderDataTable(DT::datatable({
    data <- Test_File %>%
    dplyr::select(A,B) %>%
    dplyr::mutate(URL = paste0("https://www.testsite.com/abcdefg/", 
                         A)) %>%
    dplyr::mutate(URL = paste0("<a href='", URL, "'>",A,"</a>"))
    if(input$a != "All"){
    data <- data[data$A == input$a,]
    }
    if(input$b != "All"){
    data <- data[data$B == input$b,]
    }
   data
}))

Upvotes: 2

Views: 3327

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33397

Here is a working example:

library(DT)
library(dplyr)

A <- c("Alpha", "Beta", "Gamma", "Delta")
B <- c("one","two","three","four")
C <- c("five","six","seven","eight")
Test_File <- as.data.frame(cbind(A,B,C))

ui <- basicPage(
  DT::dataTableOutput("table")
)

server <- function(input, output) {
  output$table <- DT::renderDataTable({
    data <- Test_File %>%
      dplyr::select(A,B) %>%
      dplyr::mutate(URL = paste0("https://www.testsite.com/abcdefg/", A)) %>%
      dplyr::mutate(URL = paste0("<a href='", URL, "'>",A,"</a>"))
  }, escape = FALSE)
}

shinyApp(ui, server)

You need to pass escape = FALSE as an argument to renderDataTable. Moreover, you need to drop your datatable() call because renderDataTable ignores additional arguments when you pass a datatable object to it.

Upvotes: 5

Related Questions