R Shinydashboard动态menuItem

时间:2015-09-23 13:37:07

标签: r shinydashboard

我试图动态生成多个menuItem,可能很简单,但我没有得到正确的想法。

library(shiny)
library(shinydashboard)
port_tables<-c("tab1","tab2","tab3","tab4") # These are from a DB connection in the original code
function(input, output) {
    output$smenu1 <- renderMenu({
      sidebarMenu( id = "tabs",
          h4("Tables",style="color:yellow;margin-left:20px;"),
          paste("menuItem(\"",port_tables,"\",tabName=\"",port_tables,"\",icon=icon('th'))",collapse=",")
        )
     })
  )

来自paste函数的menuItem无法解析(我在侧边栏上获得了粘贴功能的结果)。我尝试了evaleval(parse(paste(...))),两者都没有用 - 我错过了什么?

2 个答案:

答案 0 :(得分:4)

我无法弄清楚你要求的是什么,但这里有一个动态菜单的例子。

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic Menu"),
  dashboardSidebar(
    sidebarMenuOutput(outputId = "dy_menu")
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "main",
              textInput(inputId = "new_menu_name", 
                        label = "New Menu Name"),
              actionButton(inputId = "add",
                           label = "Add Menu")
      )
    )
  )
)

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

  output$dy_menu <- renderMenu({
    menu_list <- list(
      menuItem("Add Menu Items", tabName = "main", selected = TRUE),
      menu_vals$menu_list)
    sidebarMenu(.list = menu_list)
  })

  menu_vals = reactiveValues(menu_list = NULL)
  observeEvent(eventExpr = input$add,
               handlerExpr = {
                 menu_vals$menu_list[[length(menu_vals$menu_list) + 1]] <- menuItem(input$new_menu_name,
                                                                                    tabName = input$new_menu_name) 
               })

}

shinyApp(ui, server)

答案 1 :(得分:1)

我按如下方式修改了代码,但它确实有效:

library(shiny)
library(shinydashboard)
port_tables<-c("tab1","tab2","tab3","tab4") # These are from a DB connection in the original code
text1<-paste("menuItem(\"",port_tables,"\",tabName=\"",port_tables,"\",icon=icon('th'))")
text2<-paste("sidebarMenu(id = 'tabs',textInput('port', 'Enter port:'),h4('Tables',style='color:yellow;margin-left:20px;'),",paste(text1,collapse=","),paste(")"))
function(input, output) {
output$smenu1 <- renderMenu({
eval(parse(text=text2))
 })
)

因此,关键是将sidebarMenu的全部内容放在文本字段中并对其进行评估