Debian Codegraph @

R/loader.R

raw
1 #' Template loaders
2 #'
3 #' Loaders are responsible for exposing templates to the templating engine.
4 #'
5 #' @return A `"jinjar_loader"` object.
6 #' @seealso The loader is an argument to [jinjar_config()].
7 #' @examples
8 #' path_loader(getwd())
9 #'
10 #' package_loader("base", "demo")
11 #'
12 #' list_loader(list(
13 #' header = "Title: {{ title }}",
14 #' content = "Hello {{ person }}!"
15 #' ))
16 #' @name loader
17 NULL
18
19 new_loader <- function(..., .class = character()) {
20 structure(list(...), class = c(.class, "jinjar_loader"))
21 }
22
23 #' @description `path_loader()` loads templates from a directory in the file system.
24 #' @param ... Strings specifying path components.
25 #' @rdname loader
26 #' @export
27 path_loader <- function(...) {
28 path <- fs::path_abs(fs::path(...))
29 check_dir_exists(path)
30
31 new_loader(
32 path = path,
33 .class = "path_loader"
34 )
35 }
36
37 #' @description `package_loader()` loads templates from a directory in an R package.
38 #' @param package Name of the package in which to search.
39 #' @rdname loader
40 #' @export
41 package_loader <- function(package, ...) {
42 path <- fs::path_package(package, ...)
43 check_dir_exists(path)
44
45 new_loader(
46 path = path,
47 pkg = package,
48 rel_path = fs::path(...),
49 .class = c("package_loader", "path_loader")
50 )
51 }
52
53 #' @export
54 print.path_loader <- function(x, ...) {
55 cli::cli_text("{.strong Loader:} {.path {x$path}}")
56 invisible(x)
57 }
58
59 #' @export
60 print.package_loader <- function(x, ...) {
61 cli::cli_text("{.strong Loader:} {.pkg {{{x$pkg}}}}/{.path {x$rel_path}}")
62 invisible(x)
63 }
64
65 #' @description `list_loader()` loads templates from a named list.
66 #' @param x Named list mapping template names to template sources.
67 #' @rdname loader
68 #' @export
69 list_loader <- function(x) {
70 if (!(is_bare_list(x) && is_named(x))) {
71 cli::cli_abort("{.arg x} must be a named list", arg = "x")
72 }
73
74 do.call(new_loader, c(x, .class = "list_loader"))
75 }
76
77 #' @export
78 print.list_loader <- function(x, ...) {
79 csv_width <- sum(nchar(names(x)))
80
81 if (csv_width <= 50) {
82 cli::cli_text("{.strong Loader:} {.val {names(x)}}")
83 } else {
84 cli::cli_text("{.strong Loader:}")
85 cli::cli_ul()
86 for (name in names(x)) {
87 cli::cli_li("{.val {name}}")
88 }
89 cli::cli_end()
90 }
91
92 invisible(x)
93 }