Here's a basic example.
Assume that you have a myreport.Rmd file with the following header:
---
title: "Untitled"
author: "Romain Lesur"
date: "27 janvier 2018"
output:
html_document:
includes:
in_header: inheader.html
---
Using a hacky rmarkdown preprocessor, you can copy inheader.html file.
The following code is intended to be run in R console:
pre_processor <- function(metadata,
input_file,
runtime,
knit_meta,
files_dir,
output_dir) {
in_header <- metadata$output$html_document$includes$in_header
if (!is.null(in_header)) file.copy(in_header, output_dir)
invisible(NULL)
}
custom_output_format <- function() {
rmarkdown::output_format(
knitr = NULL,
pandoc = NULL,
pre_processor = pre_processor,
base_format = rmarkdown::html_document()
)
}
rmarkdown::render('myreport.Rmd',
output_format = custom_output_format(),
output_dir = 'output')
You get a output directory with the rendered report and inheader.html file inside.
In order to run a similar preprocessor on clicking Knit button, you have to include it in your personal package's output_format (see below).
Turning in a package
Here is an adaptation of the quarterly_report function of this blogpost:
quarterly_report <- function(toc = TRUE) {
# get the locations of resource files located within the package
css <- system.file("reports/styles.css", package = "mypackage")
header <- system.file("reports/quarterly/header.html", package = "mypackage")
# call the base html_document function
base_format <-
rmarkdown::html_document(toc = toc,
fig_width = 6.5,
fig_height = 4,
theme = NULL,
css = css,
includes = includes(before_body = header))
pre_processor <- function(metadata,
input_file,
runtime,
knit_meta,
files_dir,
output_dir) {
purrr::walk(c(css, header), file.copy, output_dir)
invisible(NULL)
}
rmarkdown::output_format(
knitr = NULL,
pandoc = NULL,
pre_processor = pre_processor,
base_format = base_format
)
}
This solution is not 100% satisfying because I don't think that rmarkdown pre_processor was created for having side-effects. But it works.