如何在Shiny app中捕获动态tabPanel()id

时间:2017-06-29 14:35:45

标签: shiny

可以将tabPanel id用于链接吗?我说的是像#tab-6584-1 #tab-6985-1 这样的ID,当你的光标位于浏览器中运行的Shiny应用中的标签上时,它会显示:

Image of dynamic tabPanel() id example with Firefox

我想使用此功能在Shiny应用中放置一个左上角的链接,以便在应用“主页”页面上重定向。

1 个答案:

答案 0 :(得分:0)

从您的问题来看,我不确定,但似乎您想模仿导航到&#34;子页面&#34;在你的应用程序中如果是这种情况,可以通过在应用程序的URL(link to gist)末尾读取和写入哈希字符串的值来在Shiny中执行此操作:< / p>

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      tags$a("Go to Panel 1", href = "#panel1"), br(),
      tags$a("Go to Panel 2", href = "#panel2"), br(),
      tags$a("Go to Panel 3", href = "#panel3")
    ),
    mainPanel(
      tabsetPanel(id = "tabs",
        tabPanel("Panel 1", h1("Panel 1"), value = "#panel1"),
        tabPanel("Panel 2", h1("Panel 2"), value = "#panel2"),
        tabPanel("Panel 3", h1("Panel 3"), value = "#panel3")
      )
    )
  )
)
server <- function(input, output, session) {
  # When we change from one `tabPanel` to another, update the URL hash
  observeEvent(input$tabs, {

    # No work to be done if input$tabs and the hash are already the same
    if (getUrlHash() == input$tabs) return()

    # The 'push' argument is necessary so that the hash change event occurs and
    # so that the other observer is triggered.
    updateQueryString(
      paste0(getQueryString(), input$tabs),
      "push"
    )
    # Don't run the first time so as to not generate a circular dependency 
    # between the two observers
  }, ignoreInit = TRUE)

  # When the hash changes (due to clicking on the link in the sidebar or switching
  # between the `tabPanel`s), switch tabs and update an input. Note that clicking 
  # another `tabPanel` already switches tabs.
  observeEvent(getUrlHash(), {
    hash <- getUrlHash()

    # No work to be done if input$tabs and the hash are already the same
    if (hash == input$tabs) return()

    valid <- c("#panel1", "#panel2", "#panel3")

    if (hash %in% valid) {
      updateTabsetPanel(session, "tabs", hash)
    }
  })
}

shinyApp(ui, server)