rshinydatatablesdtsparklines

Why are the icons not displaying in a DT::datatable in Shiny app?


I'm having some trouble displaying icons with sparklines within a DT::datatable column in a Shiny app even though I have escaped the HTML.

Edit: Removed 2nd question.

library(shiny)
library(dplyr)

ui <- fluidPage(

  htmlwidgets::getDependency('sparkline'),

  DT::dataTableOutput("table")

)

server <- function(input, output) {

    raw_data <- data.frame(date = 2000:2021,
                     value = sample(100:500, 22),
                     icon = as.character(icon("arrow-up")))

  data <- raw_data %>%
    group_by(icon) %>%
    # Create the sparkline
    summarise("value" = sparkline::spk_chr(c(value),
                                xvalues = date,
                                tooltipFormat = '{{x}}: {{y}}'))

  output$table <- DT::renderDataTable({

    cb <- htmlwidgets::JS('function(){debugger;HTMLWidgets.staticRender();}')

    DT::datatable(data = data,
              escape = FALSE,
              options = list(drawCallback = cb))
  })

}

shinyApp(ui, server)

Solution

  • By default, the shiny::icon function:

    1. generates the HTML code corresponding to the icon;

    2. generates a script tag which includes the font-awesome icon library.

    When you do as.character(icon(......, you only get the HTML code. The font-awesome library is not loaded, that's why the icon does not display.

    The simplest way to get the icon is to use the glyphicon icon library, which is included in bootstrap so there's nothing to load (since bootstrap is loaded in Shiny apps):

    as.character(icon("arrow-up", lib = "glyphicon"))
    

    If you really want a font-awesome icon, there are two possibilities:

    # add inside ui
    tags$span(icon("tag"), style = "display: none;")