Skip to content

Commit

Permalink
Document how to preserve length-1 vector
Browse files Browse the repository at this point in the history
Fixes #27
  • Loading branch information
davidchall committed Nov 1, 2023
1 parent 3801ade commit 2fc494e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
9 changes: 8 additions & 1 deletion R/render.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
#' * A path to a template file (use [fs::path()]).
#' * A parsed template (use [parse_template()]).
#' @param ... <[`dynamic-dots`][rlang::dyn-dots]> Data passed to the template.
#'
#' By default, a length-1 vector is passed as a scalar variable. Use [I()] to
#' declare that a vector should be passed as an array variable. This preserves
#' a length-1 vector as an array.
#' @inheritParams parse
#' @return String containing rendered template.
#'
Expand All @@ -18,7 +22,10 @@
#' # pass data as arguments
#' render("Hello {{ name }}!", name = "world")
#'
#' # pass data as list
#' # pass length-1 vector as array
#' render("Hello {{ name.0 }}!", name = I("world"))
#'
#' # pass data programmatically
#' params <- list(name = "world")
#' render("Hello {{ name }}!", !!!params)
#'
Expand Down
11 changes: 9 additions & 2 deletions man/render.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion vignettes/template-syntax.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,16 @@ Although we pass R objects to `render()`, it is helpful to understand that these
| Data frame | Array of objects | `{{ foo.1.bar }}` |

You can use dot (`.`) notation to access data nested within a variable.
An array element is accessed by its numeric index (e.g. `foo.1`) and an object value is accessed by its key (e.g. `foo.bar`).
An array element is accessed by its numeric **zero-based** index (e.g. `foo.1`) and an object value is accessed by its key (e.g. `foo.bar`).

**Note:** In R, the dot is a valid character in an object name (e.g. `my.data`).
However, this causes ambiguity when accessing nested data values.
For this reason, each dot is replaced with an underscore when the data is encoded as JSON (e.g. `my.data` becomes `my_data`).

**Note:** In R, a scalar is indistinguishable from a length-1 vector.
This creates an ambiguity when passing R data to the template, because template variables support both scalars and arrays.
You can explicitly pass a length-1 vector as an array using the `I()` operator (see `help("render")`).

The double-brace syntax is used to print the value of the variable (e.g. `{{ foo }}`).
To use the variable in other contexts (e.g. control structures), then these braces are omitted (e.g. `{% for bar in foo %}`).

Expand Down

0 comments on commit 2fc494e

Please sign in to comment.