Debian Codegraph @

R/parse.R

raw
1 #' Parse a template
2 #'
3 #' Sometimes you want to render multiple copies of a template, using different
4 #' sets of data variables. [parse_template()] returns an intermediate version
5 #' of the template, so you can [render()] repeatedly without re-parsing the
6 #' template syntax.
7 #'
8 #' @param .x The template. Choices:
9 #' * A template string.
10 #' * A path to a template file (use [fs::path()]).
11 #' @param .config The engine configuration. The default matches Jinja defaults,
12 #' but you can use [jinjar_config()] to customize things like syntax delimiters,
13 #' whitespace control, and loading auxiliary templates.
14 #' @return A `"jinjar_template"` object.
15 #'
16 #' @seealso
17 #' * [render()] to render the final document using data variables.
18 #' * [`print()`][print.jinjar_template()] for pretty printing.
19 #' * `vignette("template-syntax")` describes how to write templates.
20 #' @examples
21 #' x <- parse_template("Hello {{ name }}!")
22 #'
23 #' render(x, name = "world")
24 #' @name parse
25 #' @export
26 parse_template <- function(.x, .config) {
27 UseMethod("parse_template")
28 }
29
30 #' @rdname parse
31 #' @export
32 parse_template.character <- function(.x, .config = default_config()) {
33 check_string(.x)
34 check_inherits(.config, "jinjar_config")
35
36 with_catch_cpp_errors({
37 parsed <- parse_(.x, .config)
38 })
39
40 structure(
41 .x,
42 config = .config,
43 parsed = parsed,
44 class = "jinjar_template"
45 )
46 }
47
48 #' @rdname parse
49 #' @export
50 parse_template.fs_path <- function(.x, .config = default_config()) {
51 read_utf8 <- function(path) {
52 paste(readLines(path, encoding = "UTF-8", warn = FALSE), collapse = "\n")
53 }
54
55 if (inherits(.config$loader, "path_loader")) {
56 if (!fs::path_has_parent(.x, .config$loader$path)) {
57 .x <- fs::path_abs(.x, .config$loader$path)
58 }
59 }
60
61 check_file_exists(.x)
62
63 parse_template(read_utf8(.x), .config)
64 }