htmlrautomationfilenamesquarto

How to dynamically set html filename when rendering Quarto documents in R


I have a parameterized Quarto document, and want to automate the rendering and use some of those parameters in the YAML together with Sys.Date() to name the resulting html file, so that everytime i render the quarto document, the output html file does not overwrite the previous one.

I have tried the solution that works for RMarkdown shown here without success in Quarto because the key Knit does not seem to exist when used in the YAML in Quarto, so the html is made with the same name as the .qmd file. Here is a minimal example of what I tried based on the link i mentioned above

---
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)
---

I also tried the keys output-file and output-ext as shown here for quarto documents, but it can only be used with strings without code looks like, so the YAML below does not work either.

---
params:
   variable = "variable1"
format:
   html: 
    output-file: "`r paste0("file_name","_",params$variable)`"
    output-ext:  "html"
title: "Testing Output filename"
--- 

Trying output-file: "File {{< meta params.variable>}}" in the last YAML did not work either (although this approach does work when used in the title: key).

So, I would like to automate generation of the html filename by adding the relevant code in the YAML, if possible. Any help appreciated, thanks!


Solution

  • It may be a janky way of doing what you are after, but why don't you create a template qmd file with variable placeholders. Since it is just a plain text document, you can read it in using R, then replace the placeholders with text you need (date etc.) and then generate a new qmd file with the correct file name and date. This file can be rendered using quarto::quarto_render("document.qmd"). Something along these lines:

    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)
    

    Template file code here:

    ---
    title: "Example"
    author: "Anthony"
    date: "::date_placeholder::"
    output: html_document
    ---