You need to enable JavaScript to run this app. 如何基于Shiny输入值显示或隐藏R flexdashboard组件
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Shiny输入值显示或隐藏R flexdashboard组件

你遇到的问题是两个原因共同导致的:

  1. renderPrint的输出会被自动包裹在<pre>标签中作为纯文本展示,不会被解析为Markdown或HTML。
  2. flexdashboard的章节布局结构是在文档初始渲染(Knitting)阶段通过Markdown解析生成的,运行时Shiny交互阶段动态输出的Markdown语法不会被重新解析,因此直接输出### Section C无法被识别为新的三级组件。

下面是两种常用的可行实现方案:


方案1:使用conditionalPanel(最简实现)

如果你的组件结构是固定的,只是需要根据输入控制显隐,直接用Shiny自带的conditionalPanel即可,不需要动态生成Markdown:

---
title: "Sample Flexdashboard"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
radioButtons(
  "select",
  "Show or hide component",
  choices = c("Show" = "show", "Hide" = "hide"),
  selected = "show"
)

Column

Section A

Section B

Section C

conditionalPanel(
  condition = "input.select == 'show'",
  # 这里填写Section C的所有内容,示例如下:
  h4("Section C的内容"),
  plotOutput("plot_c")
)
# 单独定义组件内的输出逻辑
output$plot_c <- renderPlot({
  plot(1:10, rnorm(10))
})
如果需要连`Section C`的标题一起隐藏,可以给标题所在的组件添加自定义类配合CSS控制,或者使用方案2。

---

### 方案2:使用`renderUI`动态生成完整组件
如果需要完全动态生成组件的标题和内容,用`renderUI`直接生成HTML结构:
```r
---
title: "Sample Flexdashboard"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
radioButtons(
  "select",
  "Show or hide component",
  choices = c("Show" = "show", "Hide" = "hide"),
  selected = "show"
)

Column

Section A

Section B

uiOutput("dynamic_section")
output$dynamic_section <- renderUI({
  if(input$select == "show") {
    tagList(
      # 生成符合flexdashboard规范的三级标题
      h3("Section C", class = "section level3"),
      # 组件内容
      h4("动态生成的Section C内容"),
      renderPlot(plot(1:10, rnorm(10)))
    )
  }
})
如果偏好使用Markdown语法编写动态内容,可以结合`markdown::markdownToHTML`将Markdown文本转为HTML后输出:
```r
output$dynamic_section <- renderUI({
  if(input$select == "show") {
    md_content <- "
### Section C
这里是用Markdown写的内容:
+ 列表项1
+ 列表项2
    "
    HTML(markdown::markdownToHTML(text = md_content, fragment.only = TRUE))
  }
})

内容的提问来源于stack exchange,提问作者Jacob Rothschild

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 15:15:00