如何用Quarto生成含shinylive-r的自包含HTML文件?
问题:Quarto生成含{shinylive-r}代码块的自包含HTML失败
问题描述
尝试用Quarto创建包含{shinylive-r}代码块的自包含HTML文件,但启用self-contained: true时出现异常;移除该选项后HTML可正常渲染,但需求是生成单个自包含文件。
复现步骤
- 创建名为
matts_reports.qmd的文件,内容如下:
--- title: "My document" format: html filters: - shinylive self-contained: true --- # Hello, world! ## shinylive Code Block Here is a shinylive codeblock: ```{shinylive-r} #| standalone: true #| viewerHeight: 800 #| library(shiny) ui <- fluidPage( titlePanel("Hello Shiny!"), sidebarLayout( sidebarPanel( sliderInput( inputId = "bins", label = "Number of bins:", min = 1, max = 50, value = 30 ) ), mainPanel( plotOutput(outputId = "distPlot") ) ) ) server <- function(input, output) { output$distPlot <- renderPlot({ x <- faithful$waiting bins <- seq(min(x), max(x), length.out = input$bins + 1) hist(x, breaks = bins, col = "#75AADB", border = "white", xlab = "Waiting time to next eruption (in mins)", main = "Histogram of waiting times" ) }) } shinyApp(ui = ui, server = server)
- 在R Studio中点击渲染按钮。
出现的问题
- shinylive代码块在浏览器中仅以纯文本形式显示,无法运行Shiny应用;
- R后台任务输出报错:
/shinylive.js (404: Not Found)
解决方案
这是因为self-contained: true默认不会嵌入shinylive的依赖资源,导致加载失败。推荐用以下方法解决:
方法1:替换为embed-resources: true
把YAML头部的self-contained: true改成embed-resources: true,该选项会自动嵌入shinylive所需的所有外部资源,生成单个自包含HTML文件:
--- title: "My document" format: html filters: - shinylive embed-resources: true ---
方法2:手动处理资源(不推荐)
如果一定要用self-contained,需要先下载shinylive的shinylive.js及配套CSS文件,在QMD中通过本地<script>和<link>标签引入,再启用self-contained。但这种方式步骤繁琐,不如方法1高效。
内容的提问来源于stack exchange,提问作者Matthew Tansley
相关产品推荐
相关产品推荐

