2

I would like to use some html in the choices in select(ize)Input. Does anyone know a simple solution how to tell shiny to treat the options as HTML?

library(shiny)

ui <- fluidPage(
  selectInput("test html use", label = "option", choices = c("<div title = 'This is option A'>opt A</div>", "opt B"))
)

server <- function(input, output) {
}

shinyApp(ui = ui, server = server)
Roelof Waaijman
  • 202
  • 1
  • 5

1 Answers1

4

In order to treat the options of a selectizeInput as HTML, the render option is the way to go. The following code will render the ordinary output:

library(shiny)

shinyApp(
  ui = fluidPage(
    br(),
    selectizeInput(
      "slctz", "Select something:",
      choices = list("option1" = "value1", "option2" = "value2"), 
      options = list( 
        render = I("{
        item: function(item, escape) { 
          return '<span>' + item.label + '</span>'; 
        },
        option: function(item, escape) { 
          return '<span>' + item.label + '</span>'; 
        }
      }")
      )
    )
  ),
  server = function(input, output) {}
)

The option field is for the list of options, while the item field is for the selected options.

So if you want to style the options and the selected options, you can do so cleanly by adding a class attribute to the span elements, and by defining your CSS classes in the UI:

ui = fluidPage(
  tags$head(
    tags$style(
      HTML(
        "
        .myoption {......}
        .myitem {......}
        "
      )
    )
  ),
  br(),
  selectizeInput(
    "slctz", "Select something:",
    choices = list("option1" = "value1", "option2" = "value2"), 
    options = list( 
      render = I("{
        item: function(item, escape) { 
          return '<span class=\"myitem\">' + item.label + '</span>'; 
        },
        option: function(item, escape) { 
          return '<span class=\"myoption\">' + item.label + '</span>'; 
        }
      }")
    )
  )
)
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • Could you please share some light in these doubts based on https://shiny.rstudio.com/articles/selectize.html? (1) It only mentions `option: function`, not `item: function`, could you explain what it does? (2) It gives an example using `choices = cbind(name = rownames(mtcars), mtcars)` but it is not working for me. Could you provide an example passing a dataframe into choices? – GitHunter0 Jan 14 '22 at 18:59