如何设置依赖Quarto文档输出格式的条件参数?
在Quarto中按输出格式设置动态参数
你之前的写法错误在于Quarto的params是顶层YAML字段,不能嵌套在具体格式的配置项中,所以渲染时会找不到params对象。下面提供两种可行的解决方法:
方法1:在代码中根据当前输出格式动态设置参数
直接在代码块里判断当前渲染的格式,切换对应的参数值。这种方式直观且易维护:
完整示例文档
--- title: "format-driven parameters" format: html: self-contained: true pptx: reference-doc: default.pptx ---
#| warning: false #| message: false library(ggplot2) # 获取当前输出格式 current_format <- quarto::quarto_context$format$name # 根据格式匹配对应的背景色 plot_bg <- switch(current_format, "html" = "mistyrose", "pptx" = "lightblue", "white") # 默认值 ggplot(mtcars, aes(x=drat, y=mpg)) + geom_point() + theme_minimal() + theme(plot.background = element_rect(fill = plot_bg, linetype = "blank"))
方法2:顶层定义参数,结合格式专属配置覆盖
如果想把参数集中在YAML中管理,可以先定义顶层默认参数,再通过knitr的选项在不同格式下传递专属值:
完整示例文档
--- title: "format-driven parameters" params: plot_bg: "white" # 默认背景色 format: html: knitr: opts_chunk: set: plot_bg: "mistyrose" pptx: knitr: opts_chunk: set: plot_bg: "lightblue" ---
#| warning: false #| message: false library(ggplot2) # 读取格式专属的参数值 plot_bg <- knitr::opts_chunk$get("plot_bg") ggplot(mtcars, aes(x=drat, y=mpg)) + geom_point() + theme_minimal() + theme(plot.background = element_rect(fill = plot_bg, linetype = "blank"))
注意事项
- 方法1中
quarto::quarto_context$format$name会返回当前渲染的格式名称(如html、pptx),如果需要更精确的格式标识,也可以用knitr::opts_knit$get("rmarkdown.pandoc.to")获取Pandoc目标格式。 - 两种方法都支持扩展到其他场景,比如调整字体大小、线条粗细等,只需要在条件判断中增加对应参数即可。
内容的提问来源于stack exchange,提问作者mac
相关产品推荐
相关产品推荐

