You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌入Shiny应用的Rmarkdown中DT与ggplotly无法显示求助

问题解决:Shiny嵌入Rmd后DT与ggplotly不显示

问题根源

使用includeHTML将Rmarkdown渲染的HTML嵌入Shiny应用时,DT和ggplotly生成的动态组件依赖的JavaScript/CSS资源未被Shiny的依赖管理系统正确加载。includeHTML仅插入静态HTML文本,无法注册这些动态组件所需的前端资源,导致它们无法正常渲染。

解决方案

步骤1:修改Rmarkdown模板

移除模板中的runtime: shiny(无需让Rmd自带Shiny运行时),并将输出格式改为html_fragment(生成无独立头部的HTML片段,方便嵌入Shiny):

---
title: "Test running an Rmarkdown Report via a Shiny App"
output: 
  html_fragment:
    self_contained: false
params: 
    ticker: MCO
---

步骤2:调整Shiny应用的Server逻辑

不再使用includeHTML,改为渲染HTML片段后手动附加DT和plotly的依赖资源,确保Shiny能正确加载组件所需的前端代码:

source('global.R')

ui <- fluidPage(
  selectInput(
    'ticker', 'Select ticker',
    choices = tickers ),
  uiOutput('report') # 改用uiOutput支持依赖传递
)

server <- function(input, output) {
  output$report <- renderUI({
    # 渲染Rmd为HTML片段
    rendered_html <- rmarkdown::render(
      input = 'testTemplate.Rmd',
      params = list(ticker = input$ticker),
      output_format = rmarkdown::html_fragment(self_contained = FALSE),
      quiet = TRUE
    )
    
    # 读取并拼接HTML内容
    html_content <- readLines(rendered_html, warn = FALSE) %>% 
      paste(collapse = "\n")
    
    # 创建HTML对象并附加DT和plotly的依赖
    html_obj <- htmltools::HTML(html_content)
    required_deps <- c(
      DT::datatableDependencies(),
      plotly::plotlyDependencies()
    )
    htmltools::attachDependencies(html_obj, required_deps)
  })
}

shinyApp(ui = ui, server = server)

备选简化方案(依赖预加载)

如果不想修改Rmd输出格式,可在Shiny的UI中添加占位输出,强制加载DT和plotly的依赖资源:

ui <- fluidPage(
  # 占位输出,仅用于加载依赖,无需实际渲染内容
  DT::DTOutput("dummy_dt"),
  plotly::plotlyOutput("dummy_plot"),
  
  selectInput(
    'ticker', 'Select ticker',
    choices = tickers ),
  htmlOutput('report')
)

server <- function(input, output) {
  output$report <- renderUI({
    includeHTML(
      rmarkdown::render(
        'testTemplate.Rmd',
        params = list(ticker = input$ticker)
      )
    )
  })
  
  # 占位输出的空渲染函数
  output$dummy_dt <- DT::renderDT({DT::datatable(data.frame())})
  output$dummy_plot <- plotly::renderPlotly({plotly::plot_ly()})
}

验证修改

运行修改后的Shiny应用,选择任意Ticker后,DT表格和ggplotly图表即可正常显示,kableExtra和ggplot的内容不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 12:14:56