在R Shiny的UI中包含外部文件

a8jjtwal  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(98)

我正在构建一个Shiny应用程序,以各种方式提取和可视化数据。我有几个ui小部件,我希望在悬停在小部件上时包含工具提示类型的文本。我已经成功地使用了shinyBS的bsTootip和addTooltip。在UI.r中

shinyUI(fluidPage(

    bsTooltip(id='MAPeriod',title='Enter averaging period in days. You may add more than one, separated by a space',placement='right',trigger='hover'),
    bsTooltip(id='wateryear',title='Select one or more water years. Note: there may not be data for your location and year',placement='top',trigger='hover'),
...

在server.r中

addTooltip(session,'MAPeriod',
 'Enter averaging period in days. You may add more than one, separated by a space','right')

addTooltip(session,'wateryear',
  'Select one or more water years. Note: there may not be data for your location and year','top',trigger='hover')

我用了
tags$div(title= 'Select one or more water year...', etc.
这些都工作得很好,但是当我在许多小部件中添加了工具提示时,我的代码就变得很长,很混乱,很难理解。我想将shinyBS版本添加到外部文件中,并让Shiny将它们插入正确的位置。
我在网上看了看,还没有找到任何例子,所以我想知道这是否可能,或者我是否必须生活在杂乱的环境中。任何帮助将不胜感激。

fwzugrvs

fwzugrvs1#

始终可以为工具提示创建一个专用的新文件,也可以为工具提示创建多个文件。

工具提示文件示例

在这个示例文件中,每个工具提示及其关联的服务器都 Package 在一个函数中。这可防止全局对象四处浮动。我们将在下一个文件中使用这些对象

    • tooltips.R**
# Tooltip file

# MA Period Tool Tips
MAPeriod_ui <- function() {
  shinyBS::bsTooltip(
    id = 'MAPeriod',
    title = 'Enter averaging period in days. You may add more than one, separated by a space',
    placement = 'right',
    trigger = 'hover'
  )
}

MAPeriod_server <- function(session) {
  shinyBS::addTooltip(
    session,
    'MAPeriod',
    'Enter averaging period in days. You may add more than one, separated by a space',
    'right'
  )
}

# Other tooltips...

使用工具提示文件

要使用工具提示文件,我们将对其进行源代码并将其放置到新环境中。你可以随便叫它什么,在这里我叫它tooltips。要访问在该文件中创建的工具提示,只需使用$索引tooltips环境,然后将该对象作为函数调用。示例如下。

    • app.R**
library(shiny)

# load the tooltips into a new environment
tooltips <- new.env()
source("tooltips.R", local = tooltips)

ui <- fluidPage(
  # add the tooltips using the new environment we created
  tooltips$MAPeriod_ui()
)

server <- function(input, output, session) {
  # add the tooltip server as well, making sure to pass the session to the fxn
  tooltips$MAPeriod_server(session)
}

shinyApp(ui, server)

当然,你不必将对象存储为函数,但这样更安全。您还可以创建多个工具提示文件,并将其全部源代码导入tooltips env中。
让我知道如果这对你有意义!

相关问题