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

问题描述 投票:0回答:1

我有一个参数化的四开文档,并且想要自动渲染并使用 YAML 中的一些参数与

Sys.Date()
一起命名生成的 html 文件,这样每次我渲染四开文档时,输出 html 文件就不会覆盖前一个。

我已经尝试了适用于here所示的RMarkdown的解决方案,但在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-file
output-ext
键(如 here 所示)用于四开文档,但它只能与没有代码的字符串一起使用,因此下面的 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 文件名。任何帮助表示感谢,谢谢!

html r automation filenames quarto
1个回答
0
投票

这可能是一种笨拙的方式来做你想做的事情,但为什么不创建一个带有可变占位符的 tempplace 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 variable 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)
© www.soinside.com 2019 - 2024. All rights reserved.