在R中渲染Quarto文档时如何动态设置HTML文件名

3
我有一个带参数的Quarto文档,并且想要自动化渲染并在YAML中使用其中一些参数与Sys.Date()一起命名生成的html文件,以便每次渲染Quarto文档时,输出的html文件不会覆盖之前的文件。
我尝试了在RMarkdown中有效的解决方案(here),但在Quarto中却没有成功,因为在Quarto的YAML中使用时,键Knit似乎不存在,所以html文件与.qmd文件具有相同的名称。以下是我根据上述链接尝试的最简示例。
---
title: "Example"
author: "Anthony"
date: "`r Sys.Date()`"
output: html_document
params:
   variable: "var1"
knit: >
  (function(input_file, encoding) {
    metadata <- rmarkdown::yaml_front_matter(input_file)
    output_file <- with(metadata, paste0(title,"_",params$variable, "_", author, "_",date))
    rmarkdown::render(input = input_file, output_file = output_file)
---

我也尝试了键output-fileoutput-ext,如这里所示,用于quarto文档,但它只能用于没有代码外观的字符串,所以下面的YAML也不起作用。
---
params:
   variable = "variable1"
format:
   html: 
    output-file: "`r paste0("file_name","_",params$variable)`"
    output-ext:  "html"
title: "Testing Output filename"
--- 

尝试在最后的YAML中使用output-file: "File {{< meta params.variable>}}"也没有起作用(尽管在title:键中使用这种方法是有效的)。
因此,如果可能的话,我想通过在YAML中添加相关代码来自动化生成HTML文件名。非常感谢您的帮助!

也许这可以给你一些指引:https://quarto.org/docs/authoring/variables.html#meta - undefined
@Julian,谢谢,我也尝试过了,但不幸的是没有成功。我会相应地更新问题。 - undefined
1个回答

1
这可能是一个有点笨拙的方法来实现你想要的效果,但为什么不创建一个带有变量占位符的模板 qmd 文件呢?由于它只是一个纯文本文档,你可以使用 R 读取它,然后用你需要的文本(日期等)替换占位符,然后生成一个带有正确文件名和日期的新的 qmd 文件。可以使用 quarto::quarto_render("document.qmd") 来渲染这个文件。大致就是这样的思路:
library(tidyverse)
library(quarto)

# you need to change the path to your template file
quarto_code_template <- read_file(r"{C:\Users\novot\Desktop\template.txt}")

output_file_name <- Sys.Date() %>%
  as.character() %>%
  paste0(".qmd")

# replacing the date placeholder with the actual date
quarto_code_actual <- quarto_code_template %>%
  str_replace("::date_placeholder::", as.character(Sys.Date()) )

# generating the quarto code file
write_file(quarto_code_actual, output_file_name)

# rendering an html document from the quarto file
quarto::quarto_render(output_file_name)

模板文件代码如下:
---
title: "Example"
author: "Anthony"
date: "::date_placeholder::"
output: html_document
---

谢谢,我不太确定我理解了,你能给个简单的例子吗? - undefined
@ForEverNewbie编辑了我的答案,为您提供了一个最简示例,演示如何将日期整合到输出的HTML文件和Markdown文本中。 - undefined
这个很好用,谢谢!每次渲染文档时它也会生成一个新的.qmd文件,但这只是一个小的不便。 - undefined
1
@ForEverNewbie 你可以使用R中的file.remove函数随时删除文件。 - undefined
哦,那是真的,再次感谢!很抱歉我的回答没有提到你,不知怎么回事,当评论添加到帖子中时,"@用户名"部分被删除了。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接