| 1 |
#' Render a template |
| 2 |
#' |
| 3 |
#' Data is passed to a template to render the final document. |
| 4 |
#' |
| 5 |
#' @param .x The template. Choices: |
| 6 |
#' * A template string. |
| 7 |
#' * A path to a template file (use [fs::path()]). |
| 8 |
#' * A parsed template (use [parse_template()]). |
| 9 |
#' @param ... <[`dynamic-dots`][rlang::dyn-dots]> Data passed to the template. |
| 10 |
#' |
| 11 |
#' By default, a length-1 vector is passed as a scalar variable. Use [I()] to |
| 12 |
#' declare that a vector should be passed as an array variable. This preserves |
| 13 |
#' a length-1 vector as an array. |
| 14 |
#' @inheritParams parse |
| 15 |
#' @return String containing rendered template. |
| 16 |
#' |
| 17 |
#' @seealso |
| 18 |
#' * [parse_template()] supports parsing a template once and rendering multiple |
| 19 |
#' times with different data variables. |
| 20 |
#' * `vignette("template-syntax")` describes how to write templates. |
| 21 |
#' @examples |
| 22 |
#' # pass data as arguments |
| 23 |
#' render("Hello {{ name }}!", name = "world") |
| 24 |
#' |
| 25 |
#' # pass length-1 vector as array |
| 26 |
#' render("Hello {{ name.0 }}!", name = I("world")) |
| 27 |
#' |
| 28 |
#' # pass data programmatically |
| 29 |
#' params <- list(name = "world") |
| 30 |
#' render("Hello {{ name }}!", !!!params) |
| 31 |
#' |
| 32 |
#' # render template file |
| 33 |
#' \dontrun{ |
| 34 |
#' render(fs::path("template.txt"), name = "world") |
| 35 |
#' } |
| 36 |
#' @export |
| 37 |
render <- function(.x, ...) { |
| 38 |
UseMethod("render") |
| 39 |
} |
| 40 |
|
| 41 |
#' @rdname render |
| 42 |
#' @export |
| 43 |
render.character <- function(.x, ..., .config = default_config()) { |
| 44 |
render(parse_template(.x, .config), ...) |
| 45 |
} |
| 46 |
|
| 47 |
#' @rdname render |
| 48 |
#' @export |
| 49 |
render.fs_path <- function(.x, ..., .config = default_config()) { |
| 50 |
render(parse_template(.x, .config), ...) |
| 51 |
} |
| 52 |
|
| 53 |
#' @rdname render |
| 54 |
#' @export |
| 55 |
render.jinjar_template <- function(.x, ...) { |
| 56 |
with_catch_cpp_errors({ |
| 57 |
render_(attr(.x, "parsed"), encode(...)) |
| 58 |
}) |
| 59 |
} |