---
title: "Programming with Templates in R"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Template Programming in R}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---


## Programming with Templates

```{r results='asis', echo=FALSE}
cat(gsub("\\n   ", "", packageDescription("templates", fields = "Description")))
```


## Installation


### From GitHub

```{r eval = FALSE}
devtools::install_github("wahani/templates")
```

### From CRAN

```{r eval = FALSE}
install.packages("templates")
```


## Some examples

### MySQL Queries:

Actually this package does not aim at providing parameterized sql-like queries;
but it implements the core idea behind it. Here we can use R-snippets inside
expressions, characters, or functions to inject code:

```{r}
library("templates")
library("magrittr")

sqlTemplate <- tmpl(
  ~ `SELECT *
   FROM someTable
   WHERE something IN {{ collapseInParan(ids) }};`
)

collapseInParan <- function(x) {
  # just a helper function
  paste("(", paste(x, collapse = ", "), ")")
}

tmplUpdate(
  sqlTemplate,
  ids = 1:10
)
```

The double `{` denote a region to be evaluated. They can contain arbitrary
R-code.


### Functions:

This may be useful to inject code into functions. For example to minimize the
need to query a database for simple requests when other options - like closures -
are not feasible.

```{r}
tFun <- function() {
  s <- "great idea!!!"
  cat({{ toupper(begin) }}, s, "\n")
  invisible(NULL)
}

tmpl(tFun, begin ~ "This is a")
```


### Expressions:

This might be helpful whenever we need to reuse 'code' where the environment
where it is evaluated has special meaning. This, for example, can be used to
implement parameterized reactive expressions in a shiny app.

```{r}
tExpr <- tmpl( ~ {
  cat({{ toupper(begin) }}, "\n")
})

tmpl(tExpr, begin ~ "hi")
tmplAsFun(tExpr, begin ~ "hi")()
tmplEval(tExpr, begin ~ "hi")
```


### Character:

The leading example of using characters as template are parameterized sql
queries. Like any other template they can represent also R-code and then later
be evaluated.

```{r}
tChar <- tmpl('{
  cat({{ toupper(begin) }}, "\n")
}')

tChar %>%
  tmpl(begin ~ "hi") %>%
  tmplEval
```
