selectizeInput with image / icon

时间:2017-10-08 19:13:17

标签: javascript r shiny

我想知道是否有可能在闪亮中创建像“selectIcon”这样的东西。我希望有一个只带有图标的选择器,例如颜色。

selectizeInput('colours', '',
               choices = c("blue", "red"),
               selected = "blue")

但是“蓝色”和“红色”这些词我想显示彩色方块。这也应该是所选选项的情况。假设我的所有选项都有.png个文件。如何在selectizeInput()

中包含这些文件

这是一个与this one非常相似的问题,但由于我对js一无所知,因此没有可行的解决方案。

我试过这样的事情

  selectizeInput('colours', '',
                 choices = c("blue", "red"),
                 selected = "blue",
                 options = list(render = I(
                   "{
                   option: function(item, escape) {
                   return '<div><img src=\"item.png\" width = 20 />' + escape(item.name) + '</div>'
                   }
                   }"))

但没有任何成功。选项现在是undefined。没有数字显示。

我感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用包shinyWidgets执行此类操作(此答案有偏见,我是此包的作者):

library("shiny")
library("shinyWidgets")

ui <- fluidPage(
  br(),

  pickerInput(
    inputId = "one", 
    label = "Choose:", 
    choices = c("red", "blue", "green"),
    choicesOpt = list(content = sprintf(
      "<div style='background: %s;'>&nbsp;</div>",
      c("red", "blue", "green")
    ))
  ),
  verbatimTextOutput(outputId = "resone"),

  pickerInput(
    inputId = "two", 
    label = "Choose:", 
    choices = c("home", "search", "ok-sign"),
    choicesOpt = list(
      icon = c("glyphicon-home", 
               "glyphicon-search", 
               "glyphicon-ok-sign")
    )
  ),
  verbatimTextOutput(outputId = "restwo")


)

server <- function(input, output, session) {

  output$resone <- renderPrint(input$one)

  output$restwo <- renderPrint(input$two)

}

shinyApp(ui = ui, server = server)

selectizeInput的解决方案是将您的图片放在app目录中名为www的文件夹中,然后执行此操作:

library("shiny")

# dummies images
png(filename = "www/red.png")
plot.new()
rect(0, 0, 1, 1, col = "red")
dev.off()

png(filename = "www/blue.png")
plot.new()
rect(0, 0, 1, 1, col = "blue")
dev.off()


# images are displayed only in dropdown menu
ui <- fluidPage(
  br(),
  selectizeInput(
    'colours', '',
    choices = c("blue" = "blue.png", "red" = "red.png"),
    selected = "blue",
    options = list(
      render = I(
        "{
      option: function(item, escape) {
      return '<div><img src=\"' + item.value + '\" width = 20 />' + escape(item.name) + '</div>'
      }
      }")
    )
  )
)

server <- function(input, output, session) {



}

shinyApp(ui = ui, server = server)

编辑:在shiny的最新版本中,将item.name替换为item.label