Debian Codegraph @

vignettes/template-syntax.Rmd

raw
1 ---
2 title: "Template Syntax"
3 output: rmarkdown::html_vignette
4 vignette: >
5 %\VignetteIndexEntry{Template Syntax}
6 %\VignetteEngine{knitr::rmarkdown}
7 %\VignetteEncoding{UTF-8}
8 ---
9
10 ```{r, include=FALSE}
11 knitr::opts_chunk$set(
12 collapse = TRUE,
13 comment = "#>"
14 )
15 ```
16
17 This vignette describes the template syntax supported by jinjar, following the structure of the Jinja [Template Designer Documentation](https://jinja.palletsprojects.com/templates/).
18 It is designed to act as a reference when writing templates.
19
20 The jinjar R package is powered by the [inja](https://github.com/pantor/inja) C++ library.
21 The syntax is very similar to that of the Jinja Python package, but there are also many differences.
22 Unfortunately, this means jinjar is not a drop-in replacement for Jinja -- you might need to adapt existing Jinja templates for the jinjar engine.
23
24 The most fundamental difference between jinjar and Jinja is:
25
26 * Jinja variables support direct interaction with the underlying Python objects.
27 * jinjar variables are simple [JSON data types](https://www.w3schools.com/js/js_json_datatypes.asp). The underlying R objects are translated to JSON.
28
29 This is described in more detail in the [Variables](#variables) section below.
30
31 Before starting, let's create a few R objects for rendering example templates.
32
33 ```{r setup}
34 library(jinjar)
35
36 # length-1 vector
37 title <- "My Webpage"
38
39 # vector
40 users <- c("User A", "User B", "User C")
41
42 # list
43 godzilla <- list(
44 Name = "Godzilla",
45 Born = 1952,
46 Birthplace = "Japan"
47 )
48
49 # data frame
50 navigation <- data.frame(
51 caption = c("Home", "Blog"),
52 href = c("index.html", "blog.html")
53 )
54
55 # HTML special characters
56 name <- 'Dwayne "The Rock" Johnson'
57 ```
58
59 ```{r, include=FALSE}
60 params <- list(
61 title = title,
62 users = users,
63 godzilla = godzilla,
64 navigation = navigation,
65 name = name
66 )
67 ```
68
69
70 ## Synopsis
71
72 A jinjar template is simply a text file, and when rendered the output is also a text file (e.g. HTML, SQL, LaTeX).
73
74 A template contains **variables** and/or **expressions**, which get replaced with values when a template is rendered; and **tags**, which control the logic of the template.
75
76 Below is a minimal template that illustrates a few basics using the default jinjar configuration.
77 We will cover the details later in this document:
78
79 ```{jinjar, data=params, engine.opts=list(lang="html")}
80 <!DOCTYPE html>
81 <html lang="en">
82 <head>
83 <title>{{ title }}</title>
84 </head>
85 <body>
86 <ul id="navigation">
87 {% for item in navigation -%}
88 <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
89 {% endfor -%}
90 </ul>
91 {# a comment #}
92 </body>
93 </html>
94 ```
95
96 The following example shows the default configuration settings, but you can adjust the syntax configuration as desired using `jinjar_config()`.
97
98 There are a few kinds of delimiters. The default delimiters are configured as follows:
99
100 * `{% ... %}` for [Statements](#control-structures)
101 * `{{ ... }}` for [Expressions](#expressions) to print to the template output
102 * `{# ... #}` for [Comments](#comments) not included in the template output
103
104 [Line Statements](#line-statements) are also possible, though they don’t have default prefix characters.
105 To use them, set `line_statement` when creating the `jinjar_config()`.
106
107
108 ## Variables {#variables}
109
110 When writing a template, we refer to variables that act as data placeholders.
111 We define their values when rendering the template.
112
113 Although we pass R objects to `render()`, it is helpful to understand that these are encoded as JSON objects before the template is rendered.
114
115 | R object | JSON object | Template example |
116 |:----------------|:-----------------|:------------------|
117 | Length-1 vector | Scalar | `{{ foo }}` |
118 | Vector | Array | `{{ foo.1 }}` |
119 | List | Object | `{{ foo.bar }}` |
120 | Data frame | Array of objects | `{{ foo.1.bar }}` |
121
122 You can use dot (`.`) notation to access data nested within a variable.
123 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`).
124
125 **Note:** In R, the dot is a valid character in an object name (e.g. `my.data`).
126 However, this causes ambiguity when accessing nested data values.
127 For this reason, each dot is replaced with an underscore when the data is encoded as JSON (e.g. `my.data` becomes `my_data`).
128
129 **Note:** In R, a scalar is indistinguishable from a length-1 vector.
130 This creates an ambiguity when passing R data to the template, because template variables support both scalars and arrays.
131 You can explicitly pass a length-1 vector as an array using the `I()` operator (see `help("render")`).
132
133 The double-brace syntax is used to print the value of the variable (e.g. `{{ foo }}`).
134 To use the variable in other contexts (e.g. control structures), then these braces are omitted (e.g. `{% for bar in foo %}`).
135
136 If a template variable has not been defined, then an error occurs.
137 However, you can use the `default(foo, bar)` function to specify a fallback value.
138
139
140 ## Comments {#comments}
141
142 To comment-out some lines, preventing them from appearing in the rendered document, use the comment syntax (default: `{# ... #}`).
143 This is useful for debugging or documenting the template.
144
145 ```{jinjar}
146 Hello{# TODO: update this #}!
147 ```
148
149
150 ## Whitespace Control {#whitespace}
151
152 In the default configuration, whitespace (e.g. spaces, tabs, newlines) is left unchanged in the rendered output.
153 For example, in the default configuration we get:
154
155 ```{jinjar, engine.opts=list(lang="html")}
156 <div>
157 {% if true %}
158 yay
159 {% endif %}
160 </div>
161 ```
162
163 By setting `trim_blocks = TRUE` when creating the `jinjar_config()`, the first newline after a control block is automatically removed.
164 Setting `lstrip_blocks = TRUE` removes any whitespace from the beginning of the line until the start of each block.
165 With both options enabled, the above example becomes:
166
167 ```{jinjar, engine.opts=list(lang="html", config=jinjar_config(trim_blocks=TRUE, lstrip_blocks=TRUE))}
168 <div>
169 {% if true %}
170 yay
171 {% endif %}
172 </div>
173 ```
174
175 Instead of changing the global configuration, you can manually trim whitespace at a more finegrained level.
176
177 * By putting a minus sign (`-`) after the opening delimiter, this removes any whitespace from the beginning of the line until the start of the block (i.e. the same as the `lstrip_blocks` feature).
178 * By putting a minus sign (`-`) before the closing delimiter, this removes any whitespace (including newlines) until the next non-whitespace character (i.e. slightly different from the `trim_blocks` feature).
179
180 This can be activated for control blocks, comments, or variable expressions:
181
182 ```{jinjar, engine.opts=list(lang="html")}
183 <div>
184 {% if true -%}
185 yay
186 {%- endif -%}
187 </div>
188 ```
189
190
191 ## Line Statements {#line-statements}
192
193 If line statements are enabled (see `jinjar_config()`), it’s possible to mark a line as a statement.
194 For example, if the line statement prefix is configured to `#`, you can do:
195
196 ```{jinjar, data=params, engine.opts=list(lang="html", config=jinjar_config(line_statement="#"))}
197 <ul id="navigation">
198 # for item in navigation
199 <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
200 # endfor
201 </ul>
202 ```
203
204
205 ## Control Structures {#control-structures}
206
207 A control structure refers to all those things that control the flow of a program.
208 With the default syntax, control structures appear inside `{% ... %}` blocks.
209
210
211 ### For
212
213 A for-loop allows you to iterate over each element in a vector:
214
215 ```{jinjar, data=params, engine.opts=list(lang="markdown")}
216 {% for user in users -%}
217 {{ loop.index1 }}. {{ user }}
218 {%- endfor -%}
219 ```
220
221 or loop over key-value pairs in a named list:
222
223 ```{jinjar, data=params, engine.opts=list(lang="html")}
224 <dl>
225 {% for key, value in godzilla %}
226 <dt>{{ key }}</dt>
227 <dd>{{ value }}</dd>
228 {% endfor -%}
229 </dl>
230 ```
231
232 As described in [Variables](#variables), a data frame is translated to an array of JSON objects.
233 Therefore a nested combination of the above two loops could theoretically be used.
234 In practice, it is much more common to iterate over rows and access the individual elements by their attributes:
235
236 ```{jinjar, data=params, engine.opts=list(lang="html", config=jinjar_config(line_statement="#"))}
237 <ul id="navigation">
238 {% for item in navigation -%}
239 <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
240 {% endfor -%}
241 </ul>
242 ```
243
244 While inside a for-loop block, you can access some special variables:
245
246 | Variable | Description |
247 |:----------------|:------------|
248 | `loop.index` | The current iteration (0-based). |
249 | `loop.index1` | The current iteration (1-based). |
250 | `loop.is_first` | True if first iteration. |
251 | `loop.is_last` | True if last iteration. |
252 | `loop.parent` | In nested loops, the parent loop variable. |
253
254
255 ### If
256
257 Conditional branches are written using `if`, `else if` and `else` statements, which evaluate [Expressions](#expressions).
258
259 ```{jinjar, data=params, engine.opts=list(lang="markdown")}
260 {% if length(users) > 5 -%}
261 {% for user in users -%}
262 * {{ user }}
263 {% endfor %}
264 {% else if length(users) > 0 -%}
265 {{ join(users, ", ") }}.
266 {% else -%}
267 No users found.
268 {% endif %}
269 ```
270
271
272 ### Assignments
273
274 Using the `set` statement, you can assign values to variables.
275
276 ```{jinjar}
277 {% set name="world" -%}
278 Hello {{ name }}!
279 ```
280
281
282 ### Extends
283
284 The `extends` tag can be used for template inheritance.
285 See _Template Inheritance_ in `vignette("auxiliary-templates")`.
286
287
288 ### Include
289
290 The `include` tag inserts the rendered contents of an auxiliary template.
291 See _Template Inclusion_ in `vignette("auxiliary-templates")`.
292
293
294 ## Expressions {#expressions}
295
296 Basic expressions are supported in templates.
297
298 ### Literals
299
300 The simplest form of expressions are literals, which represent fixed values.
301
302 As described in [Variables](#variables), the template is rendered using data stored in JSON format.
303 For this reason, literals must also be specified in [JSON format](https://www.w3schools.com/js/js_json_datatypes.asp).
304 The following types of literals are supported:
305
306 * **String:** characters between double quotation marks.
307 * Double quotation marks in the string value must be escaped using a backslash.
308 * **Integer:** whole numbers without decimal part.
309 * **Numeric:** floating point numbers.
310 * Specify in decimal or scientific format.
311 * **Boolean:** either `true` or `false`.
312 * Specify using lowercase characters.
313 * **List:** array of values between square brackets.
314 * **Object:** key-value data pairs between curly brackets
315 * Keys must be string literals, but values can be any literal type.
316 * **NULL:** missing data is represented by `null`.
317
318 Here is example usage for each type:
319
320 ```{jinjar}
321 String: {{ "A string" }}
322 Integer: {{ 3 }}
323 Numeric: {{ 3.14 }} or {{ 1.6e-19 }}
324 Boolean: {{ true }} or {{ false }}
325 List: {{ [1, 2, 3] }}
326 Object: {{ {"a": 1, "b": 2} }}
327 Null: {{ null }}
328 ```
329
330
331 ### Math
332
333 You can perform simple arithmetic using standard operators:
334
335 ```{jinjar}
336 1 + 1: {{ 1 + 1 }}
337 3 - 2: {{ 3 - 2 }}
338 2 * 2: {{ 2 * 2 }}
339 1 / 2: {{ 1 / 2 }}
340 2 ^ 3: {{ 2 ^ 3 }}
341 7 % 3: {{ 7 % 3 }}
342 ```
343
344
345 ### Comparisons
346
347 You can perform comparisons:
348
349 ```{jinjar}
350 1 == 1: {{ 1 == 1 }}
351 1 != 1: {{ 1 != 1 }}
352 2 > 1: {{ 2 > 1 }}
353 2 >= 1: {{ 2 >= 1 }}
354 2 < 1: {{ 2 < 1 }}
355 2 <= 1: {{ 2 <= 1 }}
356 ```
357
358
359 ### Logic
360
361 Within expressions and control structures, you can use the Boolean operators: `and`, `or`, and `not`.
362
363 ```{jinjar}
364 true and false: {{ true and false }}
365 true or false: {{ true or false }}
366 not false: {{ not false }}
367 ```
368
369 You can also check if a value is contained within a list using `in`:
370
371 ```{jinjar}
372 {{ 1 in [1, 2, 3] }}
373 ```
374
375
376 ## Functions
377
378 ### Data Checks
379
380 You can check if a value exists by passing the variable name as a string:
381
382 ```{jinjar, data=params}
383 users does exist: {{ exists("users") }}
384 abc doesn't exist: {{ exists("abc") }}
385 ```
386
387 Similarly, you can check if a value exists within a JSON object, by passing the key as a string:
388
389 ```{jinjar, data=params}
390 Birthplace does exist: {{ existsIn(godzilla, "Birthplace") }}
391 Weight doesn't exist: {{ existsIn(godzilla, "Weight") }}
392 ```
393
394 Concisely handle missing values using the `default()` function:
395
396 ```{jinjar, data=params}
397 {{ default(godzilla.Weight, 20000) }}
398 ```
399
400 You can also check the data type of a variable or literal:
401
402 ```{jinjar}
403 {{ isString("a string") }}
404 {{ isInteger(3) }}
405 {{ isFloat(3.14) }}
406 {{ isNumber(3) }} and {{ isNumber(3.14) }}
407 {{ isBoolean(false) }}
408 {{ isArray([1, 2, 3]) }}
409 {{ isObject({"a": 1, "b": 2}) }}
410 ```
411
412
413 ### Data Conversion
414
415 You can convert strings to numeric types, using the `int()` or `float()` functions:
416
417 ```{jinjar}
418 {{ int("2") }}
419 {{ float("2.5") }}
420 ```
421
422
423 ### HTML Escaping {#html-escaping}
424
425 When generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML.
426 The special characters are: `<`, `>`, `&` and `"`.
427
428 In jinjar, it's **your** responsibility to manually escape variables, using the `escape_html()` function.
429 You should escape variables that _might_ contain any of the special characters.
430 But if a variable is trusted to contain well-formed HTML, then it should not be escaped (otherwise you could accidentally double-escape the content).
431
432 ```{jinjar, data=params, engine.opts=list(lang="html")}
433 <input type="text" value="{{ escape_html(name) }}">
434 ```
435
436
437 ### SQL Quoting {#sql-quoting}
438
439 SQL databases expect string literals to be wrapped in single-quotes, while other types of literals (e.g., numbers) are not quoted.
440 This is cumbersome to achieve when writing a template, so the `quote_sql()` function provides this functionality.
441
442 **Important:** `quote_sql()` does not provide any protection against SQL injection attacks.
443
444 ```{jinjar, data=params, engine.opts=list(lang="sql")}
445 WHERE title = {{ quote_sql(title) }} AND year = {{ quote_sql(godzilla.Born) }}
446 ```
447
448 When passed an array, `quote_sql()` will quote each element and return a comma-separated list.
449 This is particularly helpful when using the SQL `IN` operator.
450
451 ```{jinjar, data=params, engine.opts=list(lang="sql")}
452 WHERE user IN ({{ quote_sql(users) }})
453 ```
454
455
456 ### Numeric Data
457
458 You can check if an integer is even or odd, or divisible by some other integer.
459 This could be used to make alternating row colors.
460
461 ```{jinjar}
462 {{ even(42) }}
463 {{ odd(42) }}
464 {{ divisibleBy(42, 7) }}
465 ```
466
467 You can round floating point numbers to a specific precision:
468
469 ```{jinjar}
470 {{ round(3.1415, 0) }}
471 {{ round(3.1415, 3) }}
472 ```
473
474
475 ### String Data
476
477 Translate a string to lower case or upper case:
478
479 ```{jinjar}
480 {{ lower("Hello") }}
481 {{ upper("Hello") }}
482 ```
483
484 Escape special characters for use in HTML content (see [HTML Escaping](#html-escaping)):
485
486 ```{jinjar, data=params, engine.opts=list(lang="html")}
487 <input type="text" value="{{ escape_html(name) }}">
488 ```
489
490 Quote string data for use as string literals in a SQL query (see [SQL Quoting](#sql-quoting)):
491
492 ```{jinjar, data=params, engine.opts=list(lang="sql")}
493 WHERE user IN ({{ quote_sql(users) }})
494 ```
495
496
497 ### JSON Lists
498
499 Get the number of list elements:
500
501 ```{jinjar}
502 length(): {{ length([3,1,2]) }}
503 ```
504
505 Get the first or last elements:
506
507 ```{jinjar}
508 first(): {{ first([3,1,2]) }}
509 last(): {{ last([3,1,2]) }}
510 ```
511
512 Get the minimum or maximum elements:
513
514 ```{jinjar}
515 min(): {{ min([3,1,2]) }}
516 max(): {{ max([3,1,2]) }}
517 ```
518
519 Sort the list into ascending order:
520
521 ```{jinjar}
522 sort(): {{ sort([3,1,2]) }}
523 ```
524
525 Join a list with a separator:
526
527 ```{jinjar, data=params}
528 {{ join([1,2,3], " + ") }}
529 {{ join(users, ", ") }}
530 ```
531
532 Generate a list as a range of integers:
533
534 ```{jinjar}
535 {% for i in range(4) %}{{ loop.index1 }}{% endfor %}
536 ```
537
538 Access elements using a dynamic index with `at()`.
539 Note that the index is **zero-based**.
540
541 ```{jinjar}
542 {% set x = [1,2,3] -%}
543 {% set i = 2 -%}
544 {{ x.2 }}
545 {{ at(x, i) }}
546 ```
547
548
549 ### JSON Objects
550
551 Access values using a dynamic key with `at()`:
552
553 ```{jinjar}
554 {% set x = {"a": 1, "b": 2} -%}
555 {% set key = "b" -%}
556 {{ x.b }}
557 {{ at(x, key) }}
558 ```
559