rr-markdownknitrquarto

Add code to HTML header in Quarto without modifying the preamble


I am writing an R package which needs to add JavaScript functions to the <head> of an HTML file created by Rmarkdown or Quarto. I do not have control over the YAML preamble, so I cannot use include-in-header. I need a programmatic way to modify the HTML header.

Ideally, I would also be able to inspect the header to avoid inserting the duplicated scripts.

I tried using knitr::knit_meta_add() but I can't figure out how it works.

# This does not appear to work
k <- list("name" = "demo", src = "https://examples.org/", script = "demo.js")
knitr::knit_meta_add(list(k))

# I do not understand how this works
knitr::knit_meta_add(list(rmarkdown::html_dependency_font_awesome()))

Solution

  • You should be able to use htmltools::htmlDependency()

    Like if I was trying to recreate knitr::knit_meta_add(list(rmarkdown::html_dependency_font_awesome())), I could by:

    metadata <- list(htmltools::htmlDependency(
      name ="font-awesome", 
      version = "6.4.2", 
      src = list("fontawesome"), 
      stylesheet = c("css/all.min.css", "css/v4-shims.min.css"), 
      package = "fontawesome", 
      all_files = TRUE))
    
    knitr::knit_meta_add(metadata)