rshinydt

stripes for DT::datatable


I am hoping to get a repeated pattern for the datatable in the code below where 3 rows are colored followed by 3 in white, then again colored... Can somebody please help me with code for that?

Also, in my Shiny app there are several tables each of which may need different styles. Would appreciate an answer which shows how the style can be tied to a particular table so that I can use that to develop other styles for the other tables.

require(shiny)
require(DT)

MkDF <- function(nr) { data.frame(value1=1:nr, value2=runif(nr)) }

server <- function(input, output) {
    ds <- MkDF(15)
    output$tbl = DT::renderDataTable({ 
        DT::datatable(ds, options=list(info=F, searching=F, paging=F),
            container= htmltools::tags$table(class="stripe row-border"),
            colnames=c("My Value1","My Value2")) %>% formatRound(2,2)
    })
}

ui <- shinyUI(
    navbarPage("Example",
        tabPanel("DT", fluidRow( column(offset=2, width=4, DT::dataTableOutput('tbl') ) ) )
    )
)

shinyApp(ui=ui, server=server)

Solution

  • You can try using the following rowCallback funtion:

    DT::datatable(ds,
     options=list(info=F, searching=F, paging=F,
     rowCallback=JS(
      'function(row,data) {
         if($(row)["0"]["_DT_RowIndex"] % 6 <3) 
                $(row).css("background","orange")
       }'))) %>% formatRound("value2",2)  
    

    Basically you can get the DT row index $(row)["0"]["_DT_RowIndex"] and use the modulo % operator to color rows.