Brent Thorne | 06ae3ac | 2018-11-30 15:16:47 -0500 | [diff] [blame] | 1 | find_file <- function(template, file) { |
| 2 | template <- system.file("rmarkdown", "templates", template, file, |
| 3 | package = "posterdown") |
| 4 | if (template == "") { |
| 5 | stop("Couldn't find template file ", template, "/", file, call. = FALSE) |
| 6 | } |
| 7 | |
| 8 | template |
| 9 | } |
| 10 | |
| 11 | find_resource <- function(template, file) { |
| 12 | find_file(template, file.path("resources", file)) |
| 13 | } |
| 14 | |
| 15 | knitr_fun <- function(name) utils::getFromNamespace(name, 'knitr') |
| 16 | |
| 17 | output_asis <- knitr_fun('output_asis') |
| 18 | |
| 19 | merge_list <- function(x, y) { |
| 20 | fun <- knitr_fun('merge_list') |
| 21 | fun(as.list(x), y) |
| 22 | } |
| 23 | |
| 24 | #' Render a pandoc template. |
| 25 | #' |
| 26 | #' This is a hacky way to access the pandoc templating engine. |
| 27 | #' |
| 28 | #' @param metadata A named list containing metadata to pass to template. |
| 29 | #' @param template Path to a pandoc template. |
| 30 | #' @param output Path to save output. |
| 31 | #' @return (Invisibly) The path of the generate file. |
| 32 | #' @examples |
| 33 | #' x <- posterdown:::template_pandoc( |
| 34 | #' list(preamble = "%abc", filename = "wickham"), |
| 35 | #' posterdown:::find_resource("posterdown_generic", "template.tex"), |
| 36 | #' tempfile() |
| 37 | #' ) |
| 38 | #' if (interactive()) file.show(x) |
| 39 | #' @noRd |
| 40 | template_pandoc <- function(metadata, template, output, verbose = FALSE) { |
| 41 | tmp <- tempfile(fileext = ".md") |
| 42 | on.exit(unlink(tmp)) |
| 43 | |
| 44 | cat("---\n", file = tmp) |
| 45 | cat(yaml::as.yaml(metadata), file = tmp, append = TRUE) |
| 46 | cat("---\n", file = tmp, append = TRUE) |
| 47 | cat("\n", file = tmp, append = TRUE) |
| 48 | |
| 49 | rmarkdown::pandoc_convert(tmp, "markdown", output = output, |
| 50 | options = paste0("--template=", template), verbose = verbose) |
| 51 | |
| 52 | invisible(output) |
| 53 | } |
| 54 | |
| 55 | |
| 56 | # Call rmarkdown::pdf_document and mark the return value as inheriting pdf_document |
| 57 | inherit_pdf_document <- function(...) { |
| 58 | fmt <- rmarkdown::pdf_document(...) |
| 59 | fmt$inherits <- "pdf_document" |
| 60 | fmt |
| 61 | } |
| 62 | |
| 63 | # Helper function to create a custom format derived from pdf_document |
| 64 | # that includes a custom LaTeX template and custom CSL definition |
| 65 | pdf_document_format <- function(..., format, template, csl) { |
| 66 | |
| 67 | # base format |
| 68 | fmt <- inherit_pdf_document(..., template = find_resource(format, template)) |
| 69 | |
| 70 | # add csl to pandoc_args |
| 71 | fmt$pandoc$args <- c(fmt$pandoc$args, |
| 72 | "--csl", |
| 73 | rmarkdown::pandoc_path_arg(find_resource(format, csl))) |
| 74 | |
| 75 | |
| 76 | # return format |
| 77 | fmt |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | |