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

嵌入Rmarkdown后Shiny应用布局缩小及number_sections失效问题

问题描述

开发了一个用tabsetPanel和tabPanel实现多标签页的Shiny应用,原本运行正常,但在某一标签页嵌入Rmarkdown文件后出现两个异常:

  • 整个应用尺寸被压缩缩小
  • Rmarkdown文件YAML头部设置的number_sections: true参数未生效,章节未自动编号

Shiny应用嵌入Rmarkdown后的异常效果

原代码

App.R

library(shiny)
library(rmarkdown)

ui <- fluidPage(
  titlePanel("多标签页Shiny应用"),
  tabsetPanel(
    tabPanel("主页",
             h3("欢迎页面"),
             p("这是应用的主页内容")
    ),
    tabPanel("数据摘要",
             includeMarkdown("data_summary.Rmd")
    )
  )
)

server <- function(input, output) {
  
}

shinyApp(ui = ui, server = server)

data_summary.Rmd

---
title: "数据摘要报告"
output: html_document
number_sections: true
---

## 数据概述
这是数据的基本概述内容。

## 统计分析
这里展示数据的统计分析结果。

问题原因

  1. 应用尺寸缩小:includeMarkdown()仅读取Rmarkdown转换后的静态HTML片段,而Rmarkdown默认的html_document模板自带固定宽度、内边距等样式,会覆盖ShinyfluidPage的流式布局样式,导致整体页面被压缩。
  2. number_sections失效:includeMarkdown()不会触发完整的Rmarkdown渲染流程,只是简单解析Markdown文本为HTML,因此YAML头部的配置参数无法被识别执行,章节编号功能不生效。

解决代码

优化后的App.R

library(shiny)
library(rmarkdown)

ui <- fluidPage(
  titlePanel("多标签页Shiny应用"),
  tabsetPanel(
    tabPanel("主页",
             h3("欢迎页面"),
             p("这是应用的主页内容")
    ),
    tabPanel("数据摘要",
             uiOutput("summary_report")
    )
  )
)

server <- function(input, output) {
  output$summary_report <- renderUI({
    # 预渲染Rmarkdown,确保YAML参数生效
    temp_html <- tempfile(fileext = ".html")
    rmarkdown::render(
      input = "data_summary.Rmd",
      output_file = temp_html,
      output_options = list(self_contained = FALSE)
    )
    # 嵌入渲染后的HTML,添加样式适配Shiny布局
    tags$div(
      style = "width: 100%; padding: 0 15px;",
      includeHTML(temp_html)
    )
  })
}

shinyApp(ui = ui, server = server)

data_summary.Rmd(保持不变)

---
title: "数据摘要报告"
output: html_document
number_sections: true
---

## 数据概述
这是数据的基本概述内容。

## 统计分析
这里展示数据的统计分析结果。

解决逻辑

  1. 修复尺寸问题:通过renderUI动态加载预渲染的HTML文件,在外层div中设置宽度为100%并调整内边距,让内容完全适配Shiny的流式布局,抵消Rmarkdown默认样式的影响。
  2. 激活章节编号:使用rmarkdown::render()主动执行完整的渲染流程,解析YAML头部的number_sections参数,生成带自动编号的章节后再嵌入应用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:23:00