R 4.0.4下Shiny交互式RMarkdown父子结构文档渲染异常问题
故障原因
- 子文档存在多余配置:子文档不需要单独声明
output和runtime,重复的yaml头部会导致knit_child渲染时生成额外的Pandoc原始标记,输出到页面就显示为你看到的{=html}和末尾多余的反引号。 - knitr版本兼容问题:R 3.6.2对应的旧版knitr中,knit_child默认会自动完成markdown渲染,而你当前使用的1.33版本knitr返回的是未渲染的原始markdown字符串,直接用
HTML()包裹不会解析markdown标记,最终导致标签页失效、内容显示异常。 - 场景适配错误:你之前尝试的
cat(res, sep = '\n')写法仅适用于非Shiny的普通RMarkdown文档,在Shiny组件中不能直接输出打印内容,需要传入渲染完成的HTML对象。
解决方案
步骤1:清理子文档配置
删掉child1.Rmd和child2.Rmd顶部的所有yaml内容,子文档不需要任何头部配置,直接保留正文和代码块即可,修改后的子文档示例:
Here is some text describing the chart below And this is some more text ```{r, echo = FALSE} fluidPage( fluidRow(column(6, renderPlot( iris %>% ggplot(aes(Sepal.Length, Sepal.Width)) + geom_point() ) )))
### 步骤2:修改父文档渲染逻辑 将父文档中直接调用`HTML(knitr::knit_child())`的逻辑替换为自定义的markdown转HTML方法,修改后的父文档完整代码如下:
output:
html_document:
always_allow_html: true
runtime: shiny
library(tidyverse) library(markdown) # 封装子文档渲染函数 render_child <- function(path) { md_content <- knitr::knit_child(path, quiet = TRUE) html_content <- markdown::markdownToHTML(text = md_content, fragment.only = TRUE) return(HTML(html_content)) } tabsetPanel(type="tabs", id="x", tabPanel("child1", value="y", render_child('child1.Rmd') ), tabPanel("child2", value="z", render_child('child2.Rmd') ) )
### 临时兼容方案 如果不想调整代码,可直接将knitr降级到1.29版本,该版本下你原来的写法可正常运行: ```r install.packages("remotes") remotes::install_version("knitr", version = "1.29")
内容的提问来源于stack exchange,提问作者hugocosh
相关产品推荐
相关产品推荐

