whisker/ 0000755 0001751 0000144 00000000000 14343407536 011755 5 ustar hornik users whisker/NAMESPACE 0000644 0001751 0000144 00000000201 13531426273 013162 0 ustar hornik users # Generated by roxygen2: do not edit by hand
export(iteratelist)
export(rowSplit)
export(whisker.escape)
export(whisker.render)
whisker/man/ 0000755 0001751 0000144 00000000000 13527765260 012534 5 ustar hornik users whisker/man/delimit.Rd 0000644 0001751 0000144 00000000606 13527765260 014454 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/delim.R
\name{delimit}
\alias{delimit}
\title{enclose a key with delimiters}
\usage{
delimit(x, delim = tag2delim())
}
\arguments{
\item{x}{character with delimiter seperated with a space}
\item{delim}{character vector with escaped delimiters}
}
\description{
enclose a key with delimiters
}
\keyword{internal}
whisker/man/iteratelist.Rd 0000644 0001751 0000144 00000002402 13527765260 015352 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/iteratelist.R
\name{iteratelist}
\alias{iteratelist}
\title{Create an iteration list from a R object}
\usage{
iteratelist(x, name = "name", value = "value")
}
\arguments{
\item{x}{\code{list} or other object that will be coerced to \code{list}}
\item{name}{\code{character} name for resulting name member.}
\item{value}{\code{character} name for resulting value member.}
}
\value{
unnamed \code{list} with name value lists
}
\description{
In some case it is useful to iterate over a named \code{list} or \code{vector}
\code{iteratelist} will create a new unnamed \code{list} with name value members:
each item will be a list where 'name' is the corresponding name and 'value' is the original
value in list \code{x}.
}
\examples{
# create an iteration list from a named vector
x <- c(a=1, b=2)
iteratelist(x)
# iterate over the members of a list
x <- list(name="John", age="30", gender="male")
iteratelist(x, name="variable")
# iterate over an unnamed vector
values <- c(1,2,3,4)
template <-
'{{#values}}
* Value: {{.}}
{{/values}}'
whisker.render(template)
#or
values <- iteratelist(values, value="count")
template <-
'{{#values}}
* Value: {{count}}
{{/values}}'
whisker.render(template)
}
whisker/man/whisker-package.Rd 0000644 0001751 0000144 00000003445 13527765260 016076 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/pkg.R
\docType{package}
\name{whisker-package}
\alias{whisker-package}
\title{{{Mustache for R}}}
\description{
Whisker is a templating engine for R conforming to the Mustache specification.
Mustache is a logicless templating language, meaning that no programming source
code can be used in your templates. This may seem very limited, but Mustache is nonetheless
powerful and has the advantage of being able to be used unaltered in many programming
languages. For example it make it very easy to write a web application in R using Mustache templates
and where the browser can template using javascript's "Mustache.js"
}
\details{
Mustache (and therefore \code{whisker}) takes a simple but different approach to templating compared to
most templating engines. Most templating libraries for example \code{Sweave} and \code{brew} allow the user
to mix programming code and text throughout the template. This is powerful, but ties a template directly
to a programming language. Furthermore that approach makes it difficult to seperate programming code
from templating code.
Whisker on the other hand, takes a Mustache template and uses the variables of the current environment (or the
supplied \code{list}) to fill in the variables.
}
\examples{
template <-
'Hello {{name}}
You have just won ${{value}}!
{{#in_ca}}
Well, ${{taxed_value}}, after taxes.
{{/in_ca}}'
data <- list( name = "Chris"
, value = 10000
, taxed_value = 10000 - (10000 * 0.4)
, in_ca = TRUE
)
whisker.render(template, data)
base <-
'
Names
{{#names}}
{{> user}}
{{/names}}'
user <- '{{name}}'
names <- list(list(name="Alice"), list(name="Bob"))
whisker.render(base, partials=list(user=user))
}
whisker/man/rxsplit.Rd 0000644 0001751 0000144 00000000660 13527765260 014532 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/delim.R
\name{rxsplit}
\alias{rxsplit}
\title{Split a character in three parts}
\usage{
rxsplit(x, pattern)
}
\arguments{
\item{x}{character text to be split}
\item{pattern}{pattern used for splitting}
}
\description{
It differs from strsplit in that it only splits on the first occurrence
and returns all parts of the string given
}
\keyword{internal}
whisker/man/whisker.render.Rd 0000644 0001751 0000144 00000002431 13527765260 015755 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/whisker.R
\name{whisker.render}
\alias{whisker.render}
\title{Logicless templating}
\usage{
whisker.render(template, data = parent.frame(), partials = list(),
debug = FALSE, strict = TRUE)
}
\arguments{
\item{template}{\code{character} with template text}
\item{data}{named \code{list} or \code{environment} with variables that will be used during rendering}
\item{partials}{named \code{list} with partial templates, will be used during template construction}
\item{debug}{Used for debugging purposes, likely to disappear}
\item{strict}{\code{logical} if \code{TRUE} the seperation symbol is a "." otherwise a "$"}
}
\value{
\code{character} with rendered template
}
\description{
Logicless templating
}
\note{
By default whisker applies html escaping on the generated text.
To prevent this use \{\{\{variable\}\}\} (triple) in stead of
\{\{variable\}\}.
}
\examples{
template <- "Hello {{place}}!"
place <- "World"
whisker.render(template)
# to prevent html escaping use triple {{{}}}
template <-
"I'm escaped: {{name}}
And I'm not: {{{name}}}"
data <- list( name = '')
whisker.render(template, data)
# I'm escaped: <My Name="Nescio&">
# And I'm not:
}
whisker/man/tag2delim.Rd 0000644 0001751 0000144 00000000612 14343404770 014663 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/delim.R
\name{tag2delim}
\alias{tag2delim}
\title{change a delimiter tag into two escaped characters}
\usage{
tag2delim(tag = "{{ }}", escape = TRUE)
}
\arguments{
\item{tag}{character with delimiter tag seperated with a space}
}
\description{
change a delimiter tag into two escaped characters
}
\keyword{internal}
whisker/man/rowSplit.Rd 0000644 0001751 0000144 00000001261 13527765260 014646 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/rowsplit.R
\name{rowSplit}
\alias{rowSplit}
\title{Split a data.frame or matrix into rows}
\usage{
rowSplit(x, ...)
}
\arguments{
\item{x}{\code{data.frame} or \code{matrix}}
\item{...}{other options will be passed onto \code{\link{split}}}
}
\description{
Utility function for splitting a data.frame into rows.
In a whisker template it can be useful to iterate over the rows of a data.frame or matrix.
For example rendering a table in HTML.
}
\examples{
dat <- head(InsectSprays)
dat <- unname(rowSplit(dat))
template <-
"{{#dat}}
count: {{count}}, spray: {{spray}}\\n
{{/dat}}"
whisker.render(template)
}
whisker/man/whisker.escape.Rd 0000644 0001751 0000144 00000000544 13527765260 015741 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/whisker.R
\name{whisker.escape}
\alias{whisker.escape}
\title{escape basic HTML characters}
\usage{
whisker.escape(x)
}
\arguments{
\item{x}{\code{character} that will be escaped}
}
\value{
HTML escaped character
}
\description{
This method is called for normal mustache keys
}
whisker/man/isFalsey.Rd 0000644 0001751 0000144 00000000561 13527765260 014604 0 ustar hornik users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/whisker.R
\name{isFalsey}
\alias{isFalsey}
\title{Is a value falsey according to Mustache specifications?}
\usage{
isFalsey(x)
}
\arguments{
\item{x}{value}
}
\value{
TRUE if falsey, otherwise FALSE
}
\description{
This function is used to test a value before rendering
}
\keyword{internal}
whisker/DESCRIPTION 0000644 0001751 0000144 00000000706 14343407536 013466 0 ustar hornik users Package: whisker
Maintainer: Edwin de Jonge
License: GPL-3
Title: {{mustache}} for R, Logicless Templating
Type: Package
LazyLoad: yes
Author: Edwin de Jonge
Description: Implements 'Mustache' logicless templating.
Version: 0.4.1
URL: https://github.com/edwindj/whisker
Suggests: markdown
RoxygenNote: 6.1.1
NeedsCompilation: no
Packaged: 2022-12-05 15:15:55 UTC; hornik
Repository: CRAN
Date/Publication: 2022-12-05 15:33:50 UTC
whisker/NEWS 0000644 0001751 0000144 00000001062 13527765260 012457 0 ustar hornik users 0.4
- Fixed issue #12: inconsistent treatment of new lines (Thanks to @danhalligan)
- Updated documentation for disabling html escaping. (issue #16)(Thanks to @ctbrown)
0.3-3
- Added an option "strict" to render. Setting it to FALSE allows for "." in names
and use "$" for splitting which is a more natural R syntax.
0.3-2
- Added a rowSplit utility function to iterate over rows of a data.frame
0.3-1
- Fixed rendering an empty template (Thanks to Hadley Wickham)
0.1
- Initial release
- Conforms to mustache specification except for delimiter switching
whisker/R/ 0000755 0001751 0000144 00000000000 13527765260 012162 5 ustar hornik users whisker/R/section.R 0000644 0001751 0000144 00000002166 13527765260 013756 0 ustar hornik users # todo add R specific things, data.frame and vector rendering
# for data.frames it should render per row (using paste)
# for vectors it should render per item (for ".")
section <- function(texts, keys, renders){
force(texts)
force(keys)
force(renders)
renderFUN <- function(value, context){
processSection(value, context, texts, keys, renders)
}
renderFUN
}
processSection <- function(value, context, texts, keys, renders){
if (isFalsey(value)){
return()
}
if (is.list(value) || is.vector(value)){
if (is.null(names(value))){
str <- sapply( value
, function(item){
context <- c(list(as.list(item)), context)
values <- lapply(keys, resolve, context=context)
renderTemplate(values, context, texts, renders)
}
)
return(paste(str, collapse=""))
} else {
context <- c(list(value), context)
}
}
values <- lapply(keys, resolve, context=context)
return(renderTemplate(values, context, texts, renders))
}
whisker/R/iteratelist.R 0000644 0001751 0000144 00000001604 13527765260 014637 0 ustar hornik users #' Create an iteration list from a R object
#'
#' In some case it is useful to iterate over a named \code{list} or \code{vector}
#' \code{iteratelist} will create a new unnamed \code{list} with name value members:
#' each item will be a list where 'name' is the corresponding name and 'value' is the original
#' value in list \code{x}.
#' @param x \code{list} or other object that will be coerced to \code{list}
#' @param name \code{character} name for resulting name member.
#' @param value \code{character} name for resulting value member.
#' @return unnamed \code{list} with name value lists
#' @example examples/iteratelist.R
#' @export
iteratelist <- function(x, name="name", value="value"){
x <- as.list(x)
nms <- names(x)
lapply( seq_along(x)
, function(i){
l <- list()
l[name] <- nms[i]
l[value] <- x[i]
l
}
)
}
whisker/R/delim.R 0000644 0001751 0000144 00000004620 13527765260 013401 0 ustar hornik users ALTDELIM <- "~~~~~~~~~~~~~ ~~~~~~~~~~~~~"
#' change a delimiter tag into two escaped characters
#'
#' @param tag character with delimiter tag seperated with a space
#' @param tag character with delimiter tag seperated with a space
#' @keywords internal
tag2delim <- function(tag="{{ }}", escape=TRUE){
delim <- strsplit(tag," ")[[1]]
if (escape)
gsub("([[{}*?+])", "\\\\\\1", delim)
else
delim
}
#' Split a character in three parts
#'
#' It differs from strsplit in that it only splits on the first occurrence
#' and returns all parts of the string given
#' @param x character text to be split
#' @param pattern pattern used for splitting
#' @keywords internal
rxsplit <- function(x, pattern){
matched <- regexpr(pattern, x)
if (matched == -1){
return(x)
}
ml <- attr(matched, "match.length")
c( substring(x,1,matched-1)
, substring(x,matched, matched+ml-1)
, substring(x, matched + ml)
)
}
#' enclose a key with delimiters
#'
#' @param x character with delimiter seperated with a space
#' @param delim character vector with escaped delimiters
#' @keywords internal
delimit <- function(x, delim=tag2delim()){
paste(delim[1], x, delim[2], sep="")
}
replace_delim_tags <- function(template){
text <- list()
defdelim <- tag2delim()
altdelim <- tag2delim(ALTDELIM, escape=FALSE)
defkeytag <- delimit("(.+?)", defdelim)
altkeytag <- delimit("\\1", altdelim)
tag <- "{{ }}"
while (!is.na(template)){
delim <- tag2delim(tag)
delimtag <- delimit(DELIM, delim)
keytag <- delimit("(.+?)", delim)
template <- inlineStandAlone(template, delim, DELIM)
rx <- rxsplit(template, delimtag)
txt <- rx[1]
if (tag != "{{ }}"){
txt <- gsub(defkeytag, altkeytag, txt)
}
txt <- gsub(keytag, "{{\\1}}", txt)
text[length(text)+1] <- txt
tag <- sub(delimtag, "\\1", rx[2])
template <- rx[3]
}
#print(text)
paste(text, collapse="")
}
literal_tags <- function(txt){
altdelim <- tag2delim(ALTDELIM)
defdelim <- tag2delim("{{ }}", escape=FALSE)
altkeytag <- delimit("(.+?)", altdelim)
defkeytag <- delimit("\\1", defdelim)
gsub(altkeytag, defkeytag, txt)
}
### quick testing
#delim2rx("<% %>")
# template <- "test {{=<% %>}} <%key%> {{key1}} <%=[[ ]]%> bla, [[key2]] [[={{ }}]] {{key3}} 1, 2, 3"
#rxsplit(template, delimtag)
# r <- replace_delim_tags(template)
# r
# literal_tags(r)
#replace_delim_tags(template) whisker/R/whisker.R 0000644 0001751 0000144 00000007505 13527765260 013770 0 ustar hornik users #' Logicless templating
#'
#' @param template \code{character} with template text
#' @param data named \code{list} or \code{environment} with variables that will be used during rendering
#' @param partials named \code{list} with partial templates, will be used during template construction
#' @param debug Used for debugging purposes, likely to disappear
#' @param strict \code{logical} if \code{TRUE} the seperation symbol is a "." otherwise a "$"
#' @return \code{character} with rendered template
#' @rdname whisker.render
#' @example examples/whisker_render.R
#' @export
#' @note
#' By default whisker applies html escaping on the generated text.
#' To prevent this use \{\{\{variable\}\}\} (triple) in stead of
#' \{\{variable\}\}.
whisker.render <- function( template
, data = parent.frame()
, partials = list()
, debug = FALSE
, strict = TRUE
){
if (is.null(template) || identical(paste(template, collapse=""), "")){
return("")
}
tmpl <- parseTemplate( template
, partials=as.environment(partials)
, debug=debug
, strict=strict
)
return(tmpl(data))
}
whisker.renderFile <- function(con
, data = parent.frame()
, partials = list()
, debug = FALSE
){
template <- paste(readLines(con), collapse='\n')
whisker.render(template, data, partials, debug)
}
# TODO change this into whisker...
whisker.future <- function( infile=stdin()
, outfile=stdout()
, data=if (!missing(infile)) parent.frame()
else NULL
, text=NULL
, render=!is.null(data)
){
if (missing(infile) && !is.null(text)){
infile <- textConnection(text)
}
template <- paste(readLines(infile), collapse="\n")
template <- parseTemplate(template)
#compile template
invisible(template)
}
renderText <- function(x, context){
paste(x, collapse=",")
}
renderHTML <- function(x, context){
whisker.escape(renderText(x))
}
renderEmpty <- function(x, context){
""
}
renderTemplate <- function(values, context, texts, renders, debug=FALSE){
s <- mapply(values, renders, FUN=function(value, render){
render(value, context)
})
sqt <- 2*seq_along(texts)-1
sqk <- 2*seq_along(s)
str <- character()
str[sqt] <- texts
str[sqk] <- s
# paste(str, collapse="", sep="")
str <- as.list(str)
str["sep"] <- ""
do.call(paste, str)
}
#' escape basic HTML characters
#'
#' This method is called for normal mustache keys
#' @export
#' @param x \code{character} that will be escaped
#' @return HTML escaped character
whisker.escape <- function(x){
x <- gsub("&", "&", x)
x <- gsub("<", "<", x)
x <- gsub(">", ">", x)
x <- gsub('"', """, x)
x
}
resolve <- function(tag, context, debug=FALSE, strict=TRUE){
if (tag=="."){
return(context[[1]])
}
split_symbol = if (strict) "." else "$"
#TODO R supports names that have a "."
# , so first search for "." and than split
keys <- strsplit(tag, split=split_symbol, fixed=TRUE)[[1]]
if (!length(keys))
return()
for (data in context){
value <- data
for (key in keys){
value <- value[[key]]
}
if (!is.null(value)) return(value)
}
}
#' Is a value falsey according to Mustache specifications?
#'
#' This function is used to test a value before rendering
#' @param x value
#' @return TRUE if falsey, otherwise FALSE
#' @keywords internal
isFalsey <- function(x){
( NROW(x)==0
|| (is.logical(x) && !x[1])
|| is.function(x)
)
}
whisker/R/partials.R 0000644 0001751 0000144 00000001717 13527765260 014132 0 ustar hornik users partial <- function(key, partials, indent=""){
force(key)
force(partials)
template <- partials[[key]]
if (is.null(template)){
# load from file?
fname <- paste(key, "mustache", sep=".")
if (file.exists(fname)){
template <- paste(readLines(fname), collapse="\n")
} else {
warning("No partial '",key, "' or file '",fname,"' found")
}
}
# should the partial template be parsed?
if (is.character(template)){
# remove key, because of possible infinite recursion
partials[[key]] <- NULL
template <- parseTemplate(template, partials)
#indent the partial template
env <- environment(template)
env$texts <- gsub("(\n)", paste("\\1", indent, sep=""), env$texts)
partials[[key]] <- template
}
renderPartial <- function(value, context){
# value is not used, since a partial has no value
tmpl <- partials[[key]]
return(tmpl(context=context))
}
renderPartial
}
whisker/R/inverted.R 0000644 0001751 0000144 00000000675 13527765260 014135 0 ustar hornik users inverted <- function(texts, keys, renders){
force(texts)
force(keys)
force(renders)
renderFUN <- function(value, context){
processInverted(value, context, texts, keys, renders)
}
renderFUN
}
processInverted <- function(value, context, texts, keys, renders){
if (!isFalsey(value)){
return()
}
values <- lapply(keys, resolve, context=context)
return(renderTemplate(values, context, texts, renders))
}
whisker/R/parseTemplate.R 0000644 0001751 0000144 00000012502 13527765260 015113 0 ustar hornik users #key type regexpr
TRIPLE <- "^\\{(.+)\\}"
AMPERSAND <- "^&(.+)"
SECTION <- "\\#([ A-z0-9.]+)"
INVERTEDSECTION <- "\\^([ A-z0-9.]+)"
ENDSECTION <- "/([ A-z0-9.]+)"
PARTIAL <- ">\\s*(.+?)\\s*"
COMMENT <- "!.+?"
DELIM <- "=\\s*(.+?)\\s*="
STANDALONE <- "[#/^][A-z0-9]+"
#keytypes
keytypes <- c("", "{}", "&", "#", "^", "/", ">")
# current parsing code is not a clean parsing state machine!
# This is partly due to that this would be clumsy in R,
# It's on my list to do the parsing in C (would be significantly faster)
parseTemplate <- function(template, partials=new.env(), debug=FALSE, strict=TRUE){
#TODO add delimiter switching
delim <- tag2delim()
template <- paste(template, collapse="\n")
template <- replace_delim_tags(template)
template <- removeComments(template, delim)
template <- inlinePartial(template, delim)
template <- inlineStandAlone2(template, delim, STANDALONE)
# template <- inlineStandAlone(template, delim, ENDSECTION)
# template <- inlineStandAlone(template, delim, SECTION)
# template <- inlineStandAlone(template, delim, INVERTEDSECTION)
KEY <- delimit("(.+?)", delim)
text <- strsplit(template, KEY)[[1]]
text <- literal_tags(text)
key <- getKeyInfo(template, KEY)
n <- nrow(key)
render <- list()
#default rendering method
render[1:n] <- list(renderHTML)
#literal rendering
literal <- key$type %in% c("{}", "&")
render[literal] <- list(renderText)
# parse sections and inverted sections
exclude <- logical(n)
insection <- integer(n)
stack <- 0L
for (i in seq_along(key$key)){
h <- stack[1]
insection[i] <- h
type <- key$type[i]
if(type %in% c("#", "^")){
# section and inverted section
stack <- c(i, stack)
} else if (type == "/"){
#end section
stack <- stack[-1]
if (key$key[h]!=key$key[i]){
stop("Template contains unbalanced closing tag. Found: '/", key$key[i], "' but expected: '/", key$key[h],"'")
}
# make a section or inverted section
idx <- which(h==insection)
kidx <- idx[-length(idx)]
renderFUN <- if (key$type[h] == "#") section
else inverted
render[h] <- list(renderFUN( text[idx]
, key$key[kidx]
, render[kidx]
)
)
} else if (type == ">"){
#partial
indent <- sub(">([ \t]*).+","\\1", key$rawkey[i])
render[i] <- list(partial(key$key[i], partials, indent))
}
}
if (length(stack) > 1){
stop("Template does not close the following tags: ", key$rawkey[stack])
}
exclude <- insection > 0
keys <- key$key[!exclude]
texts <- text[c(!exclude, TRUE)[seq_along(text)]] # only select text that is needed
renders <- render[!exclude]
compiled <- function(data=list(), context=list(data)){
values <- lapply(keys, resolve, context=context, strict=strict)
keyinfo <- key
renderTemplate( values=values
, context=context
, texts=texts
, renders=renders
, debug=debug
)
}
class(compiled) <- "template"
compiled
}
getKeyInfo <- function(template, KEY){
first <- gregexpr(KEY, template)[[1]]
last <- attr(first, "match.length") + first - 1
keys <- substring(template, first, last)
keys <- gsub(KEY, "\\1", keys)
key <- data.frame(rawkey=keys, first=first, last=last, stringsAsFactors=FALSE)
# keys should not contain white space, (triple and ampersand may contain surrounding whitespace
key$key <- gsub("\\s", "", key$rawkey)
key$type <- factor("", levels=keytypes)
key$type[grep(TRIPLE, key$rawkey)] <- "{}"
key$type[grep(AMPERSAND, key$rawkey)] <- "&"
key$type[grep(SECTION, key$rawkey)] <- "#"
key$type[grep(INVERTEDSECTION, key$rawkey)] <- "^"
key$type[grep(ENDSECTION, key$rawkey)] <- "/"
key$type[grep(PARTIAL, key$rawkey)] <- ">"
key$key <- gsub(TRIPLE, "\\1",key$key)
key$key <- gsub(AMPERSAND, "\\1",key$key)
key$key <- gsub(SECTION, "\\1",key$key)
key$key <- gsub(INVERTEDSECTION, "\\1",key$key)
key$key <- gsub(ENDSECTION, "\\1",key$key)
key$key <- gsub(PARTIAL, "\\1",key$key)
key
}
inlineStandAlone2 <- function(text, delim, keyregexp){
# remove groups from regexp
keyregexp <- gsub("\\(|\\)","",keyregexp)
dKEY <- delimit(keyregexp, delim)
re <- paste("(?<=\n|^)([ \t]*)(",dKEY,")\\s*?(\n|$)", sep="")
rex <- gregexpr(re, text, perl=T)
rex1 <- gregexpr(dKEY, text)
gsub(re, "\\2", text, perl=T)
}
inlineStandAlone <- function(text, delim, keyregexp){
# remove groups from regexp
keyregexp <- gsub("\\(|\\)","",keyregexp)
dKEY <- delimit(keyregexp, delim)
re <- paste("(^|\n)([ \t]*)(",dKEY,")\\s*?(\n|$)", sep="")
rex <- regexpr(re, text)
gsub(re, "\\1\\3", text)
}
removeComments <- function(text, delim){
text <- inlineStandAlone(text, delim, COMMENT)
#remove inline comments
dCOMMENT <- paste(delim[1],COMMENT, delim[2], sep="")
gsub(dCOMMENT, "", text)
}
inlinePartial <- function(text, delim){
dKEY <- paste(delim[1],PARTIAL, delim[2], sep="")
text <- gsub(dKEY, "{{>\\1}}", text)
re <- paste("(^|\n)([ \t]*)",dKEY,"\\s*?(\n|$)", sep="")
rep <- paste("\\1\\2", delim[1],">\\2\\3",delim[2], sep="")
gsub(re, rep, text)
}
whisker/R/markdown.R 0000644 0001751 0000144 00000002204 13527765260 014125 0 ustar hornik users # Utility for markdown files
whisker.markdownToHTML <- function( template
, data = parent.frame()
, partials = list()
, debug = FALSE
){
if (!requireNamespace("markdown", quietly = TRUE)){
stop("This function needs the package 'markdown', which can be installed from CRAN.")
}
if (is.null(template) || identical(template, "")){
return("")
}
md.tmpl <- parseTemplate(template, partials=as.environment(partials), debug=debug)
}
md <- function(x, ...){
UseMethod("md")
}
md.default <- function(x, ...){
as.character(x)
}
md.data.frame <- function(x, ...){
header <- paste(names(x), collapse="|")
line <- paste("---", collapse="|")
rows <- lapply(1:nrow(x), function(r){
paste(x[r,], collapse="|")
})
rows <- paste(rows, collapse="\n")
paste(header, line, rows, sep="\n")
}
# md.list <- function(x, indent=0, ...){
# ID <- paste(rep(" ", indent), collapse="")
# l <- sapply(x, md, indent=indent+1, ...)
# paste(ID, "*", l, collapse="\n")
# }
#
# md(head(cars))
#
# a <- list(a=1, b=list(b1=23, b2=34))
# md(a) whisker/R/rowsplit.R 0000644 0001751 0000144 00000000730 13527765260 014170 0 ustar hornik users #' Split a data.frame or matrix into rows
#'
#' Utility function for splitting a data.frame into rows.
#' In a whisker template it can be useful to iterate over the rows of a data.frame or matrix.
#' For example rendering a table in HTML.
#' @param x \code{data.frame} or \code{matrix}
#' @param ... other options will be passed onto \code{\link{split}}
#' @export
#' @example examples/rowSplit.R
rowSplit <- function(x, ...){
unname(split(x, seq_len(nrow(x)), ...))
} whisker/R/pkg.R 0000644 0001751 0000144 00000002353 13527765260 013071 0 ustar hornik users #' {{Mustache for R}}
#'
#' Whisker is a templating engine for R conforming to the Mustache specification.
#' Mustache is a logicless templating language, meaning that no programming source
#' code can be used in your templates. This may seem very limited, but Mustache is nonetheless
#' powerful and has the advantage of being able to be used unaltered in many programming
#' languages. For example it make it very easy to write a web application in R using Mustache templates
#' and where the browser can template using javascript's "Mustache.js"
#'
#' Mustache (and therefore \code{whisker}) takes a simple but different approach to templating compared to
#' most templating engines. Most templating libraries for example \code{Sweave} and \code{brew} allow the user
#' to mix programming code and text throughout the template. This is powerful, but ties a template directly
#' to a programming language. Furthermore that approach makes it difficult to seperate programming code
#' from templating code.
#'
#' Whisker on the other hand, takes a Mustache template and uses the variables of the current environment (or the
#' supplied \code{list}) to fill in the variables.
#'
#' @example examples/pkg.R
#' @name whisker-package
#' @docType package
{} whisker/MD5 0000644 0001751 0000144 00000004511 14343407536 012266 0 ustar hornik users 8541cc3343eea8180f32f2d24bfed864 *DESCRIPTION
b3cd55b2ddfa8e6bf328211ca5b9241b *NAMESPACE
cb7f9a1c05ea8f228d6df93a9453ba19 *NEWS
ea1712bff13f42ca1bc3fb105fce2677 *R/delim.R
65c8a7b4f7803710fbb6b615d7ebe7e2 *R/inverted.R
af593f5e05a8284dc793248fff037432 *R/iteratelist.R
339717c308600833c37748270d812f74 *R/markdown.R
3a0f6b08ddfde12168238b1c77f14c1b *R/parseTemplate.R
83885260a82806efa530e06a87979342 *R/partials.R
493215b07006dd09f837dbd3f9bd8421 *R/pkg.R
163b70da85eb235af407509a8e92da86 *R/rowsplit.R
0c0d3ea478e817123371e1c39ee12a16 *R/section.R
5c90542ab55a536926b13aafdeb64ca4 *R/whisker.R
9a86fcc5035602b66aa0bd7396911b13 *inst/specs/comments.json
8368fd0607bd61042807813333521d3d *inst/specs/comments.yml
c366c059488125c5409a2d29c4f97341 *inst/specs/convert.R
231d7ee8dd388946dac70d148b4757e9 *inst/specs/delimiters.json
f6d14c21ca9274dcb23a88039449f2f9 *inst/specs/delimiters.yml
763c08a8c89df2cd29939c7bd0ebd723 *inst/specs/interpolation.json
41f9f5c028bec6096c202e02d1a9e140 *inst/specs/interpolation.yml
3a96b0dc2c091f803b1d2c605a22f588 *inst/specs/inverted.json
84c2866ba6e006957681cb29a208dfcd *inst/specs/inverted.yml
04f768433cc9f99e0e8695f74e1977df *inst/specs/lambdas.json
8c7fda3726592bf0f6b2a20a5d0577c7 *inst/specs/lambdas.yml
3ca65e6da0b0c094e291a9ea5be25764 *inst/specs/partials.json
67120f3c53fa4360390d0aeb58b22b27 *inst/specs/partials.yml
74f540fbe2659fa4b03b56c8a7b8dbae *inst/specs/sections.json
2f37002778a2c0caa62f46756ad04962 *inst/specs/sections.yml
e38b2a8494a98c795bebe69e9743e7f2 *inst/tests/testComments.R
76d8e54d0e4407122f59909237eba74d *inst/tests/testName.R
3fe9391a8912e409d3393c3cb2780d60 *inst/tests/testdelimiters.R
c9264bf2c07f795bd0a11e117318f0bd *inst/tests/testinterpolation.R
4e9c2b2a44786cd953d59e6a84382f27 *inst/tests/testinverted.R
4f8db70996c8f6929698ace0a5566298 *inst/tests/testpartials.R
1a59da593b8b3297f9e5f65451fbb8ec *inst/tests/testsections.R
a223f6f6f5635eeed578cc7eea3c08a6 *man/delimit.Rd
ff7067de00d777e150106157625281bf *man/isFalsey.Rd
5ce3abc68bf4edc6a255573cb9a3620c *man/iteratelist.Rd
be7490f6378af93df4bdf05fb7d4fd69 *man/rowSplit.Rd
e558b310683ef306fdfbb2142962d09b *man/rxsplit.Rd
d015fdbe2f0570afe7aef25db039477c *man/tag2delim.Rd
21c11174db2129b91e550d878b893835 *man/whisker-package.Rd
6f7ad96ca79b6e357490451419520433 *man/whisker.escape.Rd
4e42131fdcaeca095a20f2fd588e63ff *man/whisker.render.Rd
whisker/inst/ 0000755 0001751 0000144 00000000000 13527765260 012736 5 ustar hornik users whisker/inst/specs/ 0000755 0001751 0000144 00000000000 13527765260 014053 5 ustar hornik users whisker/inst/specs/sections.json 0000644 0001751 0000144 00000016625 13527765260 016607 0 ustar hornik users {"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Section tags and End Section tags are used in combination to wrap a section\nof the template for iteration\n\nThese tags' content MUST be a non-whitespace character sequence NOT\ncontaining the current closing delimiter; each Section tag MUST be followed\nby an End Section tag with the same content within the same section.\n\nThis tag's content names the data to replace the tag. Name resolution is as\nfollows:\n 1) Split the name on periods; the first part is the name to resolve, any\n remaining parts should be retained.\n 2) Walk the context stack from top to bottom, finding the first context\n that is a) a hash containing the name as a key OR b) an object responding\n to a method with the given name.\n 3) If the context is a hash, the data is the value associated with the\n name.\n 4) If the context is an object and the method with the given name has an\n arity of 1, the method SHOULD be called with a String containing the\n unprocessed contents of the sections; the data is the value returned.\n 5) Otherwise, the data is the value returned by calling the method with\n the given name.\n 6) If any name parts were retained in step 1, each should be resolved\n against a context stack containing only the result from the former\n resolution. If any part fails resolution, the result should be considered\n falsey, and should interpolate as the empty string.\nIf the data is not of a list type, it is coerced into a list as follows: if\nthe data is truthy (e.g. `!!data == true`), use a single-element list\ncontaining the data, otherwise use an empty list.\n\nFor each element in the data list, the element MUST be pushed onto the\ncontext stack, the section MUST be rendered, and the element MUST be popped\noff the context stack.\n\nSection and End Section tags SHOULD be treated as standalone when\nappropriate.\n","tests":[{"name":"Truthy","data":{"boolean":true},"expected":"\"This should be rendered.\"","template":"\"{{#boolean}}This should be rendered.{{/boolean}}\"","desc":"Truthy sections should have their contents rendered."},{"name":"Falsey","data":{"boolean":false},"expected":"\"\"","template":"\"{{#boolean}}This should not be rendered.{{/boolean}}\"","desc":"Falsey sections should have their contents omitted."},{"name":"Context","data":{"context":{"name":"Joe"}},"expected":"\"Hi Joe.\"","template":"\"{{#context}}Hi {{name}}.{{/context}}\"","desc":"Objects and hashes should be pushed onto the context stack."},{"name":"Deeply Nested Contexts","data":{"a":{"one":1},"b":{"two":2},"c":{"three":3},"d":{"four":4},"e":{"five":5}},"expected":"1\n121\n12321\n1234321\n123454321\n1234321\n12321\n121\n1\n","template":"{{#a}}\n{{one}}\n{{#b}}\n{{one}}{{two}}{{one}}\n{{#c}}\n{{one}}{{two}}{{three}}{{two}}{{one}}\n{{#d}}\n{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}\n{{#e}}\n{{one}}{{two}}{{three}}{{four}}{{five}}{{four}}{{three}}{{two}}{{one}}\n{{/e}}\n{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}\n{{/d}}\n{{one}}{{two}}{{three}}{{two}}{{one}}\n{{/c}}\n{{one}}{{two}}{{one}}\n{{/b}}\n{{one}}\n{{/a}}\n","desc":"All elements on the context stack should be accessible."},{"name":"List","data":{"list":[{"item":1},{"item":2},{"item":3}]},"expected":"\"123\"","template":"\"{{#list}}{{item}}{{/list}}\"","desc":"Lists should be iterated; list items should visit the context stack."},{"name":"Empty List","data":{"list":[]},"expected":"\"\"","template":"\"{{#list}}Yay lists!{{/list}}\"","desc":"Empty lists should behave like falsey values."},{"name":"Doubled","data":{"two":"second","bool":true},"expected":"* first\n* second\n* third\n","template":"{{#bool}}\n* first\n{{/bool}}\n* {{two}}\n{{#bool}}\n* third\n{{/bool}}\n","desc":"Multiple sections per template should be permitted."},{"name":"Nested (Truthy)","data":{"bool":true},"expected":"| A B C D E |","template":"| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |","desc":"Nested truthy sections should have their contents rendered."},{"name":"Nested (Falsey)","data":{"bool":false},"expected":"| A E |","template":"| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |","desc":"Nested falsey sections should be omitted."},{"name":"Context Misses","data":{},"expected":"[]","template":"[{{#missing}}Found key 'missing'!{{/missing}}]","desc":"Failed context lookups should be considered falsey."},{"name":"Implicit Iterator - String","data":{"list":["a","b","c","d","e"]},"expected":"\"(a)(b)(c)(d)(e)\"","template":"\"{{#list}}({{.}}){{/list}}\"","desc":"Implicit iterators should directly interpolate strings."},{"name":"Implicit Iterator - Integer","data":{"list":[1,2,3,4,5]},"expected":"\"(1)(2)(3)(4)(5)\"","template":"\"{{#list}}({{.}}){{/list}}\"","desc":"Implicit iterators should cast integers to strings and interpolate."},{"name":"Implicit Iterator - Decimal","data":{"list":[1.1,2.2,3.3,4.4,5.5]},"expected":"\"(1.1)(2.2)(3.3)(4.4)(5.5)\"","template":"\"{{#list}}({{.}}){{/list}}\"","desc":"Implicit iterators should cast decimals to strings and interpolate."},{"name":"Dotted Names - Truthy","data":{"a":{"b":{"c":true}}},"expected":"\"Here\" == \"Here\"","template":"\"{{#a.b.c}}Here{{/a.b.c}}\" == \"Here\"","desc":"Dotted names should be valid for Section tags."},{"name":"Dotted Names - Falsey","data":{"a":{"b":{"c":false}}},"expected":"\"\" == \"\"","template":"\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\"","desc":"Dotted names should be valid for Section tags."},{"name":"Dotted Names - Broken Chains","data":{"a":{}},"expected":"\"\" == \"\"","template":"\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\"","desc":"Dotted names that cannot be resolved should be considered falsey."},{"name":"Surrounding Whitespace","data":{"boolean":true},"expected":" | \t|\t | \n","template":" | {{#boolean}}\t|\t{{/boolean}} | \n","desc":"Sections should not alter surrounding whitespace."},{"name":"Internal Whitespace","data":{"boolean":true},"expected":" | \n | \n","template":" | {{#boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n","desc":"Sections should not alter internal whitespace."},{"name":"Indented Inline Sections","data":{"boolean":true},"expected":" YES\n GOOD\n","template":" {{#boolean}}YES{{/boolean}}\n {{#boolean}}GOOD{{/boolean}}\n","desc":"Single-line sections should not alter surrounding whitespace."},{"name":"Standalone Lines","data":{"boolean":true},"expected":"| This Is\n|\n| A Line\n","template":"| This Is\n{{#boolean}}\n|\n{{/boolean}}\n| A Line\n","desc":"Standalone lines should be removed from the template."},{"name":"Indented Standalone Lines","data":{"boolean":true},"expected":"| This Is\n|\n| A Line\n","template":"| This Is\n {{#boolean}}\n|\n {{/boolean}}\n| A Line\n","desc":"Indented standalone lines should be removed from the template."},{"name":"Standalone Line Endings","data":{"boolean":true},"expected":"|\r\n|","template":"|\r\n{{#boolean}}\r\n{{/boolean}}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags."},{"name":"Standalone Without Previous Line","data":{"boolean":true},"expected":"#\n/","template":" {{#boolean}}\n#{{/boolean}}\n/","desc":"Standalone tags should not require a newline to precede them."},{"name":"Standalone Without Newline","data":{"boolean":true},"expected":"#\n/\n","template":"#{{#boolean}}\n/\n {{/boolean}}","desc":"Standalone tags should not require a newline to follow them."},{"name":"Padding","data":{"boolean":true},"expected":"|=|","template":"|{{# boolean }}={{/ boolean }}|","desc":"Superfluous in-tag whitespace should be ignored."}]} whisker/inst/specs/comments.yml 0000644 0001751 0000144 00000004677 13527765260 016441 0 ustar hornik users overview: |
Comment tags represent content that should never appear in the resulting
output.
The tag's content may contain any substring (including newlines) EXCEPT the
closing delimiter.
Comment tags SHOULD be treated as standalone when appropriate.
tests:
- name: Inline
desc: Comment blocks should be removed from the template.
data: { }
template: '12345{{! Comment Block! }}67890'
expected: '1234567890'
- name: Multiline
desc: Multiline comments should be permitted.
data: { }
template: |
12345{{!
This is a
multi-line comment...
}}67890
expected: |
1234567890
- name: Standalone
desc: All standalone comment lines should be removed.
data: { }
template: |
Begin.
{{! Comment Block! }}
End.
expected: |
Begin.
End.
- name: Indented Standalone
desc: All standalone comment lines should be removed.
data: { }
template: |
Begin.
{{! Indented Comment Block! }}
End.
expected: |
Begin.
End.
- name: Standalone Line Endings
desc: '"\r\n" should be considered a newline for standalone tags.'
data: { }
template: "|\r\n{{! Standalone Comment }}\r\n|"
expected: "|\r\n|"
- name: Standalone Without Previous Line
desc: Standalone tags should not require a newline to precede them.
data: { }
template: " {{! I'm Still Standalone }}\n!"
expected: "!"
- name: Standalone Without Newline
desc: Standalone tags should not require a newline to follow them.
data: { }
template: "!\n {{! I'm Still Standalone }}"
expected: "!\n"
- name: Multiline Standalone
desc: All standalone comment lines should be removed.
data: { }
template: |
Begin.
{{!
Something's going on here...
}}
End.
expected: |
Begin.
End.
- name: Indented Multiline Standalone
desc: All standalone comment lines should be removed.
data: { }
template: |
Begin.
{{!
Something's going on here...
}}
End.
expected: |
Begin.
End.
- name: Indented Inline
desc: Inline comments should not strip whitespace
data: { }
template: " 12 {{! 34 }}\n"
expected: " 12 \n"
- name: Surrounding Whitespace
desc: Comment removal should preserve surrounding whitespace.
data: { }
template: '12345 {{! Comment Block! }} 67890'
expected: '12345 67890'
whisker/inst/specs/convert.R 0000644 0001751 0000144 00000003333 13527765260 015660 0 ustar hornik users # Create testthat test from the specification file for Mustache, so it can be
# tested if lives up to the specification
#
# Please note:
# * You'll need rjson for reading the specifications
# * an installed whisker, because that is used for the generation of the test
# (eat your own dog food...)
library(rjson)
library(whisker)
header <-
"# Automatically generated from specification file: '{{file}}'
#
{{overview}}
library(testthat)
context('Spec v1.1, {{type}}')
"
testtemplate <-
"test_that( {{&name}}, {
#{{&desc}}
template <- {{&template}}
data <- {{&data}}
{{#partials}}
partials <- {{&partials}}
str <- whisker.render(template, partials=partials, data=data)
{{/partials}}
{{^partials}}
str <- whisker.render(template, data=data)
{{/partials}}
expect_equal(str, {{&expected}}, label=deparse(str), info={{&desc}})
})
"
convertToTest <- function(files){
for (json in files){
writeSpec(json)
}
}
writeSpec <- function(file){
outfile <- gsub("^(.+).json", "../tests/test\\1.R", file)
spec <- fromJSON(file=file)
con <- file(outfile, open="wt")
on.exit(close(con))
spec$file <- file
spec$overview <- gsub("(^|\n)", "\\1# ", spec$overview)
spec$type <- gsub(".json", "", file)
writeLines(whisker.render(header, data=spec), con)
test <- sapply(spec$test, writeTest)
writeLines(test, con)
}
writeTest <- function(test){
test <- lapply(test, deparse, control=c("keepNA"))
test$data <- paste(test$data, collapse="\n")
whisker.render(testtemplate, data=test)
}
spec <- c( "interpolation.json"
, "comments.json"
, "inverted.json"
, "sections.json"
, "partials.json"
, "delimiters.json"
#, "lambdas.json"
)
convertToTest(spec) whisker/inst/specs/lambdas.json 0000644 0001751 0000144 00000015221 13527765260 016352 0 ustar hornik users {
"overview": "Lambdas are a special-cased data type for use in interpolations and\nsections.\n\nWhen used as the data value for an Interpolation tag, the lambda MUST be\ntreatable as an arity 0 function, and invoked as such. The returned value\nMUST be rendered against the default delimiters, then interpolated in place\nof the lambda.\n\nWhen used as the data value for a Section tag, the lambda MUST be treatable\nas an arity 1 function, and invoked as such (passing a String containing the\nunprocessed section contents). The returned value MUST be rendered against\nthe current delimiters, then interpolated in place of the section.\n",
"tests": [
{
"expected": "Hello, world!",
"data": {
"lambda": {
"python": "lambda: \"world\"",
"perl": "sub { \"world\" }",
"php": "return \"world\";",
"ruby": "proc { \"world\" }",
"js": "function() { return \"world\" }"
"R": "function() { \"world\" }"
}
},
"name": "Interpolation",
"template": "Hello, {{lambda}}!",
"desc": "A lambda's return value should be interpolated."
},
{
"expected": "Hello, world!",
"data": {
"planet": "world",
"lambda": {
"python": "lambda: \"{{planet}}\"",
"perl": "sub { \"{{planet}}\" }",
"php": "return \"{{planet}}\";",
"ruby": "proc { \"{{planet}}\" }",
"js": "function() { return \"{{planet}}\" }"
"R": "function() { \"{{planet}}\" }"
}
},
"name": "Interpolation - Expansion",
"template": "Hello, {{lambda}}!",
"desc": "A lambda's return value should be parsed."
},
{
"expected": "Hello, (|planet| => world)!",
"data": {
"planet": "world",
"lambda": {
"python": "lambda: \"|planet| => {{planet}}\"",
"perl": "sub { \"|planet| => {{planet}}\" }",
"php": "return \"|planet| => {{planet}}\";",
"ruby": "proc { \"|planet| => {{planet}}\" }",
"js": "function() { return \"|planet| => {{planet}}\" }"
"R": "function() { \"|planet| => {{planet}}\" }"
}
},
"name": "Interpolation - Alternate Delimiters",
"template": "{{= | | =}}\nHello, (|&lambda|)!",
"desc": "A lambda's return value should parse with the default delimiters."
},
{
"expected": "1 == 2 == 3",
"data": {
"lambda": {
"python": "lambda: globals().update(calls=globals().get(\"calls\",0)+1) or calls",
"perl": "sub { no strict; $calls += 1 }",
"php": "global $calls; return ++$calls;",
"ruby": "proc { $calls ||= 0; $calls += 1 }",
"js": "function() { return (g=(function(){return this})()).calls=(g.calls||0)+1 }"
"R": "function(){if (!exists(\"x\")) x <<- 0; x <<- x + 1; x}"
}
},
"name": "Interpolation - Multiple Calls",
"template": "{{lambda}} == {{{lambda}}} == {{lambda}}",
"desc": "Interpolated lambdas should not be cached."
},
{
"expected": "<>>",
"data": {
"lambda": {
"python": "lambda: \">\"",
"perl": "sub { \">\" }",
"php": "return \">\";",
"ruby": "proc { \">\" }",
"js": "function() { return \">\" }"
"R": "function() { \">\"}"
}
},
"name": "Escaping",
"template": "<{{lambda}}{{{lambda}}}",
"desc": "Lambda results should be appropriately escaped."
},
{
"expected": "",
"data": {
"x": "Error!",
"lambda": {
"python": "lambda text: text == \"{{x}}\" and \"yes\" or \"no\"",
"perl": "sub { $_[0] eq \"{{x}}\" ? \"yes\" : \"no\" }",
"php": "return ($text == \"{{x}}\") ? \"yes\" : \"no\";",
"ruby": "proc { |text| text == \"{{x}}\" ? \"yes\" : \"no\" }",
"js": "function(txt) { return (txt == \"{{x}}\" ? \"yes\" : \"no\") }"
"R": "function(txt) { ifelse(txt == \"{{x}}\",\"yes\",\"no\") }"
}
},
"name": "Section",
"template": "<{{#lambda}}{{x}}{{/lambda}}>",
"desc": "Lambdas used for sections should receive the raw section string."
},
{
"expected": "<-Earth->",
"data": {
"planet": "Earth",
"lambda": {
"python": "lambda text: \"%s{{planet}}%s\" % (text, text)",
"perl": "sub { $_[0] . \"{{planet}}\" . $_[0] }",
"php": "return $text . \"{{planet}}\" . $text;",
"ruby": "proc { |text| \"#{text}{{planet}}#{text}\" }",
"js": "function(txt) { return txt + \"{{planet}}\" + txt }"
"R": "function(txt) { paste(txt, \"{{planet}}\", txt, sep=\"\"}"
}
},
"name": "Section - Expansion",
"template": "<{{#lambda}}-{{/lambda}}>",
"desc": "Lambdas used for sections should have their results parsed."
},
{
"expected": "<-{{planet}} => Earth->",
"data": {
"planet": "Earth",
"lambda": {
"python": "lambda text: \"%s{{planet}} => |planet|%s\" % (text, text)",
"perl": "sub { $_[0] . \"{{planet}} => |planet|\" . $_[0] }",
"php": "return $text . \"{{planet}} => |planet|\" . $text;",
"ruby": "proc { |text| \"#{text}{{planet}} => |planet|#{text}\" }",
"js": "function(txt) { return txt + \"{{planet}} => |planet|\" + txt }"
}
},
"name": "Section - Alternate Delimiters",
"template": "{{= | | =}}<|#lambda|-|/lambda|>",
"desc": "Lambdas used for sections should parse with the current delimiters."
},
{
"expected": "__FILE__ != __LINE__",
"data": {
"lambda": {
"python": "lambda text: \"__%s__\" % (text)",
"perl": "sub { \"__\" . $_[0] . \"__\" }",
"php": "return \"__\" . $text . \"__\";",
"ruby": "proc { |text| \"__#{text}__\" }",
"js": "function(txt) { return \"__\" + txt + \"__\" }"
}
},
"name": "Section - Multiple Calls",
"template": "{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}",
"desc": "Lambdas used for sections should not be cached."
},
{
"expected": "<>",
"data": {
"static": "static",
"lambda": {
"python": "lambda text: 0",
"perl": "sub { 0 }",
"php": "return false;",
"ruby": "proc { |text| false }",
"js": "function(txt) { return false }"
}
},
"name": "Inverted Section",
"template": "<{{^lambda}}{{static}}{{/lambda}}>",
"desc": "Lambdas used for inverted sections should be considered truthy."
}
]
} whisker/inst/specs/partials.yml 0000644 0001751 0000144 00000005702 13527765260 016421 0 ustar hornik users overview: |
Partial tags are used to expand an external template into the current
template.
The tag's content MUST be a non-whitespace character sequence NOT containing
the current closing delimiter.
This tag's content names the partial to inject. Set Delimiter tags MUST NOT
affect the parsing of a partial. The partial MUST be rendered against the
context stack local to the tag.
Partial tags SHOULD be treated as standalone when appropriate. If this tag
is used standalone, any whitespace preceding the tag should treated as
indentation, and prepended to each line of the partial before rendering.
tests:
- name: Basic Behavior
desc: The greater-than operator should expand to the named partial.
data: { }
template: '"{{>text}}"'
partials: { text: 'from partial' }
expected: '"from partial"'
- name: Context
desc: The greater-than operator should operate within the current context.
data: { text: 'content' }
template: '"{{>partial}}"'
partials: { partial: '*{{text}}*' }
expected: '"*content*"'
- name: Recursion
desc: The greater-than operator should properly recurse.
data: { content: "X", nodes: [ { content: "Y", nodes: [] } ] }
template: '{{>node}}'
partials: { node: '{{content}}<{{#nodes}}{{>node}}{{/nodes}}>' }
expected: 'X>'
# Whitespace Sensitivity
- name: Surrounding Whitespace
desc: The greater-than operator should not alter surrounding whitespace.
data: { }
template: '| {{>partial}} |'
partials: { partial: "\t|\t" }
expected: "| \t|\t |"
- name: Inline Indentation
desc: Whitespace should be left untouched.
data: { data: '|' }
template: " {{data}} {{> partial}}\n"
partials: { partial: ">\n>" }
expected: " | >\n>\n"
- name: Standalone Line Endings
desc: '"\r\n" should be considered a newline for standalone tags.'
data: { }
template: "|\r\n{{>partial}}\r\n|"
partials: { partial: ">" }
expected: "|\r\n>|"
- name: Standalone Without Previous Line
desc: Standalone tags should not require a newline to precede them.
data: { }
template: " {{>partial}}\n>"
partials: { partial: ">\n>"}
expected: " >\n >>"
- name: Standalone Without Newline
desc: Standalone tags should not require a newline to follow them.
data: { }
template: ">\n {{>partial}}"
partials: { partial: ">\n>" }
expected: ">\n >\n >"
- name: Standalone Indentation
desc: Each line of the partial should be indented before rendering.
data: { content: "<\n->" }
template: |
\
{{>partial}}
/
partials:
partial: |
|
{{{content}}}
|
expected: |
\
|
<
->
|
/
# Whitespace Insensitivity
- name: Padding Whitespace
desc: Superfluous in-tag whitespace should be ignored.
data: { boolean: true }
template: "|{{> partial }}|"
partials: { partial: "[]" }
expected: '|[]|'
whisker/inst/specs/interpolation.yml 0000644 0001751 0000144 00000017626 13527765260 017501 0 ustar hornik users overview: |
Interpolation tags are used to integrate dynamic content into the template.
The tag's content MUST be a non-whitespace character sequence NOT containing
the current closing delimiter.
This tag's content names the data to replace the tag. A single period (`.`)
indicates that the item currently sitting atop the context stack should be
used; otherwise, name resolution is as follows:
1) Split the name on periods; the first part is the name to resolve, any
remaining parts should be retained.
2) Walk the context stack from top to bottom, finding the first context
that is a) a hash containing the name as a key OR b) an object responding
to a method with the given name.
3) If the context is a hash, the data is the value associated with the
name.
4) If the context is an object, the data is the value returned by the
method with the given name.
5) If any name parts were retained in step 1, each should be resolved
against a context stack containing only the result from the former
resolution. If any part fails resolution, the result should be considered
falsey, and should interpolate as the empty string.
Data should be coerced into a string (and escaped, if appropriate) before
interpolation.
The Interpolation tags MUST NOT be treated as standalone.
tests:
- name: No Interpolation
desc: Mustache-free templates should render as-is.
data: { }
template: |
Hello from {Mustache}!
expected: |
Hello from {Mustache}!
- name: Basic Interpolation
desc: Unadorned tags should interpolate content into the template.
data: { subject: "world" }
template: |
Hello, {{subject}}!
expected: |
Hello, world!
- name: HTML Escaping
desc: Basic interpolation should be HTML escaped.
data: { forbidden: '& " < >' }
template: |
These characters should be HTML escaped: {{forbidden}}
expected: |
These characters should be HTML escaped: & " < >
- name: Triple Mustache
desc: Triple mustaches should interpolate without HTML escaping.
data: { forbidden: '& " < >' }
template: |
These characters should not be HTML escaped: {{{forbidden}}}
expected: |
These characters should not be HTML escaped: & " < >
- name: Ampersand
desc: Ampersand should interpolate without HTML escaping.
data: { forbidden: '& " < >' }
template: |
These characters should not be HTML escaped: {{&forbidden}}
expected: |
These characters should not be HTML escaped: & " < >
- name: Basic Integer Interpolation
desc: Integers should interpolate seamlessly.
data: { mph: 85 }
template: '"{{mph}} miles an hour!"'
expected: '"85 miles an hour!"'
- name: Triple Mustache Integer Interpolation
desc: Integers should interpolate seamlessly.
data: { mph: 85 }
template: '"{{{mph}}} miles an hour!"'
expected: '"85 miles an hour!"'
- name: Ampersand Integer Interpolation
desc: Integers should interpolate seamlessly.
data: { mph: 85 }
template: '"{{&mph}} miles an hour!"'
expected: '"85 miles an hour!"'
- name: Basic Decimal Interpolation
desc: Decimals should interpolate seamlessly with proper significance.
data: { power: 1.210 }
template: '"{{power}} jiggawatts!"'
expected: '"1.21 jiggawatts!"'
- name: Triple Mustache Decimal Interpolation
desc: Decimals should interpolate seamlessly with proper significance.
data: { power: 1.210 }
template: '"{{{power}}} jiggawatts!"'
expected: '"1.21 jiggawatts!"'
- name: Ampersand Decimal Interpolation
desc: Decimals should interpolate seamlessly with proper significance.
data: { power: 1.210 }
template: '"{{&power}} jiggawatts!"'
expected: '"1.21 jiggawatts!"'
# Context Misses
- name: Basic Context Miss Interpolation
desc: Failed context lookups should default to empty strings.
data: { }
template: "I ({{cannot}}) be seen!"
expected: "I () be seen!"
- name: Triple Mustache Context Miss Interpolation
desc: Failed context lookups should default to empty strings.
data: { }
template: "I ({{{cannot}}}) be seen!"
expected: "I () be seen!"
- name: Ampersand Context Miss Interpolation
desc: Failed context lookups should default to empty strings.
data: { }
template: "I ({{&cannot}}) be seen!"
expected: "I () be seen!"
# Dotted Names
- name: Dotted Names - Basic Interpolation
desc: Dotted names should be considered a form of shorthand for sections.
data: { person: { name: 'Joe' } }
template: '"{{person.name}}" == "{{#person}}{{name}}{{/person}}"'
expected: '"Joe" == "Joe"'
- name: Dotted Names - Triple Mustache Interpolation
desc: Dotted names should be considered a form of shorthand for sections.
data: { person: { name: 'Joe' } }
template: '"{{{person.name}}}" == "{{#person}}{{{name}}}{{/person}}"'
expected: '"Joe" == "Joe"'
- name: Dotted Names - Ampersand Interpolation
desc: Dotted names should be considered a form of shorthand for sections.
data: { person: { name: 'Joe' } }
template: '"{{&person.name}}" == "{{#person}}{{&name}}{{/person}}"'
expected: '"Joe" == "Joe"'
- name: Dotted Names - Arbitrary Depth
desc: Dotted names should be functional to any level of nesting.
data:
a: { b: { c: { d: { e: { name: 'Phil' } } } } }
template: '"{{a.b.c.d.e.name}}" == "Phil"'
expected: '"Phil" == "Phil"'
- name: Dotted Names - Broken Chains
desc: Any falsey value prior to the last part of the name should yield ''.
data:
a: { }
template: '"{{a.b.c}}" == ""'
expected: '"" == ""'
- name: Dotted Names - Broken Chain Resolution
desc: Each part of a dotted name should resolve only against its parent.
data:
a: { b: { } }
c: { name: 'Jim' }
template: '"{{a.b.c.name}}" == ""'
expected: '"" == ""'
- name: Dotted Names - Initial Resolution
desc: The first part of a dotted name should resolve as any other name.
data:
a: { b: { c: { d: { e: { name: 'Phil' } } } } }
b: { c: { d: { e: { name: 'Wrong' } } } }
template: '"{{#a}}{{b.c.d.e.name}}{{/a}}" == "Phil"'
expected: '"Phil" == "Phil"'
# Whitespace Sensitivity
- name: Interpolation - Surrounding Whitespace
desc: Interpolation should not alter surrounding whitespace.
data: { string: '---' }
template: '| {{string}} |'
expected: '| --- |'
- name: Triple Mustache - Surrounding Whitespace
desc: Interpolation should not alter surrounding whitespace.
data: { string: '---' }
template: '| {{{string}}} |'
expected: '| --- |'
- name: Ampersand - Surrounding Whitespace
desc: Interpolation should not alter surrounding whitespace.
data: { string: '---' }
template: '| {{&string}} |'
expected: '| --- |'
- name: Interpolation - Standalone
desc: Standalone interpolation should not alter surrounding whitespace.
data: { string: '---' }
template: " {{string}}\n"
expected: " ---\n"
- name: Triple Mustache - Standalone
desc: Standalone interpolation should not alter surrounding whitespace.
data: { string: '---' }
template: " {{{string}}}\n"
expected: " ---\n"
- name: Ampersand - Standalone
desc: Standalone interpolation should not alter surrounding whitespace.
data: { string: '---' }
template: " {{&string}}\n"
expected: " ---\n"
# Whitespace Insensitivity
- name: Interpolation With Padding
desc: Superfluous in-tag whitespace should be ignored.
data: { string: "---" }
template: '|{{ string }}|'
expected: '|---|'
- name: Triple Mustache With Padding
desc: Superfluous in-tag whitespace should be ignored.
data: { string: "---" }
template: '|{{{ string }}}|'
expected: '|---|'
- name: Ampersand With Padding
desc: Superfluous in-tag whitespace should be ignored.
data: { string: "---" }
template: '|{{& string }}|'
expected: '|---|'
whisker/inst/specs/comments.json 0000644 0001751 0000144 00000004426 13527765260 016601 0 ustar hornik users {"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Comment tags represent content that should never appear in the resulting\noutput.\n\nThe tag's content may contain any substring (including newlines) EXCEPT the\nclosing delimiter.\n\nComment tags SHOULD be treated as standalone when appropriate.\n","tests":[{"name":"Inline","data":{},"expected":"1234567890","template":"12345{{! Comment Block! }}67890","desc":"Comment blocks should be removed from the template."},{"name":"Multiline","data":{},"expected":"1234567890\n","template":"12345{{!\n This is a\n multi-line comment...\n}}67890\n","desc":"Multiline comments should be permitted."},{"name":"Standalone","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n{{! Comment Block! }}\nEnd.\n","desc":"All standalone comment lines should be removed."},{"name":"Indented Standalone","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n {{! Indented Comment Block! }}\nEnd.\n","desc":"All standalone comment lines should be removed."},{"name":"Standalone Line Endings","data":{},"expected":"|\r\n|","template":"|\r\n{{! Standalone Comment }}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags."},{"name":"Standalone Without Previous Line","data":{},"expected":"!","template":" {{! I'm Still Standalone }}\n!","desc":"Standalone tags should not require a newline to precede them."},{"name":"Standalone Without Newline","data":{},"expected":"!\n","template":"!\n {{! I'm Still Standalone }}","desc":"Standalone tags should not require a newline to follow them."},{"name":"Multiline Standalone","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n{{!\nSomething's going on here...\n}}\nEnd.\n","desc":"All standalone comment lines should be removed."},{"name":"Indented Multiline Standalone","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n {{!\n Something's going on here...\n }}\nEnd.\n","desc":"All standalone comment lines should be removed."},{"name":"Indented Inline","data":{},"expected":" 12 \n","template":" 12 {{! 34 }}\n","desc":"Inline comments should not strip whitespace"},{"name":"Surrounding Whitespace","data":{},"expected":"12345 67890","template":"12345 {{! Comment Block! }} 67890","desc":"Comment removal should preserve surrounding whitespace."}]} whisker/inst/specs/partials.json 0000644 0001751 0000144 00000005414 13527765260 016571 0 ustar hornik users {"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Partial tags are used to expand an external template into the current\ntemplate.\n\nThe tag's content MUST be a non-whitespace character sequence NOT containing\nthe current closing delimiter.\n\nThis tag's content names the partial to inject. Set Delimiter tags MUST NOT\naffect the parsing of a partial. The partial MUST be rendered against the\ncontext stack local to the tag.\n\nPartial tags SHOULD be treated as standalone when appropriate. If this tag\nis used standalone, any whitespace preceding the tag should treated as\nindentation, and prepended to each line of the partial before rendering.\n","tests":[{"name":"Basic Behavior","data":{},"expected":"\"from partial\"","template":"\"{{>text}}\"","desc":"The greater-than operator should expand to the named partial.","partials":{"text":"from partial"}},{"name":"Context","data":{"text":"content"},"expected":"\"*content*\"","template":"\"{{>partial}}\"","desc":"The greater-than operator should operate within the current context.","partials":{"partial":"*{{text}}*"}},{"name":"Recursion","data":{"content":"X","nodes":[{"content":"Y","nodes":[]}]},"expected":"X>","template":"{{>node}}","desc":"The greater-than operator should properly recurse.","partials":{"node":"{{content}}<{{#nodes}}{{>node}}{{/nodes}}>"}},{"name":"Surrounding Whitespace","data":{},"expected":"| \t|\t |","template":"| {{>partial}} |","desc":"The greater-than operator should not alter surrounding whitespace.","partials":{"partial":"\t|\t"}},{"name":"Inline Indentation","data":{"data":"|"},"expected":" | >\n>\n","template":" {{data}} {{> partial}}\n","desc":"Whitespace should be left untouched.","partials":{"partial":">\n>"}},{"name":"Standalone Line Endings","data":{},"expected":"|\r\n>|","template":"|\r\n{{>partial}}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags.","partials":{"partial":">"}},{"name":"Standalone Without Previous Line","data":{},"expected":" >\n >>","template":" {{>partial}}\n>","desc":"Standalone tags should not require a newline to precede them.","partials":{"partial":">\n>"}},{"name":"Standalone Without Newline","data":{},"expected":">\n >\n >","template":">\n {{>partial}}","desc":"Standalone tags should not require a newline to follow them.","partials":{"partial":">\n>"}},{"name":"Standalone Indentation","data":{"content":"<\n->"},"expected":"\\\n |\n <\n->\n |\n/\n","template":"\\\n {{>partial}}\n/\n","desc":"Each line of the partial should be indented before rendering.","partials":{"partial":"|\n{{{content}}}\n|\n"}},{"name":"Padding Whitespace","data":{"boolean":true},"expected":"|[]|","template":"|{{> partial }}|","desc":"Superfluous in-tag whitespace should be ignored.","partials":{"partial":"[]"}}]} whisker/inst/specs/lambdas.yml 0000644 0001751 0000144 00000012452 13527765260 016205 0 ustar hornik users overview: |
Lambdas are a special-cased data type for use in interpolations and
sections.
When used as the data value for an Interpolation tag, the lambda MUST be
treatable as an arity 0 function, and invoked as such. The returned value
MUST be rendered against the default delimiters, then interpolated in place
of the lambda.
When used as the data value for a Section tag, the lambda MUST be treatable
as an arity 1 function, and invoked as such (passing a String containing the
unprocessed section contents). The returned value MUST be rendered against
the current delimiters, then interpolated in place of the section.
tests:
- name: Interpolation
desc: A lambda's return value should be interpolated.
data:
lambda: !code
ruby: 'proc { "world" }'
perl: 'sub { "world" }'
js: 'function() { return "world" }'
php: 'return "world";'
python: 'lambda: "world"'
template: "Hello, {{lambda}}!"
expected: "Hello, world!"
- name: Interpolation - Expansion
desc: A lambda's return value should be parsed.
data:
planet: "world"
lambda: !code
ruby: 'proc { "{{planet}}" }'
perl: 'sub { "{{planet}}" }'
js: 'function() { return "{{planet}}" }'
php: 'return "{{planet}}";'
python: 'lambda: "{{planet}}"'
template: "Hello, {{lambda}}!"
expected: "Hello, world!"
- name: Interpolation - Alternate Delimiters
desc: A lambda's return value should parse with the default delimiters.
data:
planet: "world"
lambda: !code
ruby: 'proc { "|planet| => {{planet}}" }'
perl: 'sub { "|planet| => {{planet}}" }'
js: 'function() { return "|planet| => {{planet}}" }'
php: 'return "|planet| => {{planet}}";'
python: 'lambda: "|planet| => {{planet}}"'
template: "{{= | | =}}\nHello, (|&lambda|)!"
expected: "Hello, (|planet| => world)!"
- name: Interpolation - Multiple Calls
desc: Interpolated lambdas should not be cached.
data:
lambda: !code
ruby: 'proc { $calls ||= 0; $calls += 1 }'
perl: 'sub { no strict; $calls += 1 }'
js: 'function() { return (g=(function(){return this})()).calls=(g.calls||0)+1 }'
php: 'global $calls; return ++$calls;'
python: 'lambda: globals().update(calls=globals().get("calls",0)+1) or calls'
template: '{{lambda}} == {{{lambda}}} == {{lambda}}'
expected: '1 == 2 == 3'
- name: Escaping
desc: Lambda results should be appropriately escaped.
data:
lambda: !code
ruby: 'proc { ">" }'
perl: 'sub { ">" }'
js: 'function() { return ">" }'
php: 'return ">";'
python: 'lambda: ">"'
template: "<{{lambda}}{{{lambda}}}"
expected: "<>>"
- name: Section
desc: Lambdas used for sections should receive the raw section string.
data:
x: 'Error!'
lambda: !code
ruby: 'proc { |text| text == "{{x}}" ? "yes" : "no" }'
perl: 'sub { $_[0] eq "{{x}}" ? "yes" : "no" }'
js: 'function(txt) { return (txt == "{{x}}" ? "yes" : "no") }'
php: 'return ($text == "{{x}}") ? "yes" : "no";'
python: 'lambda text: text == "{{x}}" and "yes" or "no"'
template: "<{{#lambda}}{{x}}{{/lambda}}>"
expected: ""
- name: Section - Expansion
desc: Lambdas used for sections should have their results parsed.
data:
planet: "Earth"
lambda: !code
ruby: 'proc { |text| "#{text}{{planet}}#{text}" }'
perl: 'sub { $_[0] . "{{planet}}" . $_[0] }'
js: 'function(txt) { return txt + "{{planet}}" + txt }'
php: 'return $text . "{{planet}}" . $text;'
python: 'lambda text: "%s{{planet}}%s" % (text, text)'
template: "<{{#lambda}}-{{/lambda}}>"
expected: "<-Earth->"
- name: Section - Alternate Delimiters
desc: Lambdas used for sections should parse with the current delimiters.
data:
planet: "Earth"
lambda: !code
ruby: 'proc { |text| "#{text}{{planet}} => |planet|#{text}" }'
perl: 'sub { $_[0] . "{{planet}} => |planet|" . $_[0] }'
js: 'function(txt) { return txt + "{{planet}} => |planet|" + txt }'
php: 'return $text . "{{planet}} => |planet|" . $text;'
python: 'lambda text: "%s{{planet}} => |planet|%s" % (text, text)'
template: "{{= | | =}}<|#lambda|-|/lambda|>"
expected: "<-{{planet}} => Earth->"
- name: Section - Multiple Calls
desc: Lambdas used for sections should not be cached.
data:
lambda: !code
ruby: 'proc { |text| "__#{text}__" }'
perl: 'sub { "__" . $_[0] . "__" }'
js: 'function(txt) { return "__" + txt + "__" }'
php: 'return "__" . $text . "__";'
python: 'lambda text: "__%s__" % (text)'
template: '{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}'
expected: '__FILE__ != __LINE__'
- name: Inverted Section
desc: Lambdas used for inverted sections should be considered truthy.
data:
static: 'static'
lambda: !code
ruby: 'proc { |text| false }'
perl: 'sub { 0 }'
js: 'function(txt) { return false }'
php: 'return false;'
python: 'lambda text: 0'
template: "<{{^lambda}}{{static}}{{/lambda}}>"
expected: "<>"
whisker/inst/specs/sections.yml 0000644 0001751 0000144 00000017741 13527765260 016437 0 ustar hornik users overview: |
Section tags and End Section tags are used in combination to wrap a section
of the template for iteration
These tags' content MUST be a non-whitespace character sequence NOT
containing the current closing delimiter; each Section tag MUST be followed
by an End Section tag with the same content within the same section.
This tag's content names the data to replace the tag. Name resolution is as
follows:
1) Split the name on periods; the first part is the name to resolve, any
remaining parts should be retained.
2) Walk the context stack from top to bottom, finding the first context
that is a) a hash containing the name as a key OR b) an object responding
to a method with the given name.
3) If the context is a hash, the data is the value associated with the
name.
4) If the context is an object and the method with the given name has an
arity of 1, the method SHOULD be called with a String containing the
unprocessed contents of the sections; the data is the value returned.
5) Otherwise, the data is the value returned by calling the method with
the given name.
6) If any name parts were retained in step 1, each should be resolved
against a context stack containing only the result from the former
resolution. If any part fails resolution, the result should be considered
falsey, and should interpolate as the empty string.
If the data is not of a list type, it is coerced into a list as follows: if
the data is truthy (e.g. `!!data == true`), use a single-element list
containing the data, otherwise use an empty list.
For each element in the data list, the element MUST be pushed onto the
context stack, the section MUST be rendered, and the element MUST be popped
off the context stack.
Section and End Section tags SHOULD be treated as standalone when
appropriate.
tests:
- name: Truthy
desc: Truthy sections should have their contents rendered.
data: { boolean: true }
template: '"{{#boolean}}This should be rendered.{{/boolean}}"'
expected: '"This should be rendered."'
- name: Falsey
desc: Falsey sections should have their contents omitted.
data: { boolean: false }
template: '"{{#boolean}}This should not be rendered.{{/boolean}}"'
expected: '""'
- name: Context
desc: Objects and hashes should be pushed onto the context stack.
data: { context: { name: 'Joe' } }
template: '"{{#context}}Hi {{name}}.{{/context}}"'
expected: '"Hi Joe."'
- name: Deeply Nested Contexts
desc: All elements on the context stack should be accessible.
data:
a: { one: 1 }
b: { two: 2 }
c: { three: 3 }
d: { four: 4 }
e: { five: 5 }
template: |
{{#a}}
{{one}}
{{#b}}
{{one}}{{two}}{{one}}
{{#c}}
{{one}}{{two}}{{three}}{{two}}{{one}}
{{#d}}
{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}
{{#e}}
{{one}}{{two}}{{three}}{{four}}{{five}}{{four}}{{three}}{{two}}{{one}}
{{/e}}
{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}
{{/d}}
{{one}}{{two}}{{three}}{{two}}{{one}}
{{/c}}
{{one}}{{two}}{{one}}
{{/b}}
{{one}}
{{/a}}
expected: |
1
121
12321
1234321
123454321
1234321
12321
121
1
- name: List
desc: Lists should be iterated; list items should visit the context stack.
data: { list: [ { item: 1 }, { item: 2 }, { item: 3 } ] }
template: '"{{#list}}{{item}}{{/list}}"'
expected: '"123"'
- name: Empty List
desc: Empty lists should behave like falsey values.
data: { list: [ ] }
template: '"{{#list}}Yay lists!{{/list}}"'
expected: '""'
- name: Doubled
desc: Multiple sections per template should be permitted.
data: { bool: true, two: 'second' }
template: |
{{#bool}}
* first
{{/bool}}
* {{two}}
{{#bool}}
* third
{{/bool}}
expected: |
* first
* second
* third
- name: Nested (Truthy)
desc: Nested truthy sections should have their contents rendered.
data: { bool: true }
template: "| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |"
expected: "| A B C D E |"
- name: Nested (Falsey)
desc: Nested falsey sections should be omitted.
data: { bool: false }
template: "| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |"
expected: "| A E |"
- name: Context Misses
desc: Failed context lookups should be considered falsey.
data: { }
template: "[{{#missing}}Found key 'missing'!{{/missing}}]"
expected: "[]"
# Implicit Iterators
- name: Implicit Iterator - String
desc: Implicit iterators should directly interpolate strings.
data:
list: [ 'a', 'b', 'c', 'd', 'e' ]
template: '"{{#list}}({{.}}){{/list}}"'
expected: '"(a)(b)(c)(d)(e)"'
- name: Implicit Iterator - Integer
desc: Implicit iterators should cast integers to strings and interpolate.
data:
list: [ 1, 2, 3, 4, 5 ]
template: '"{{#list}}({{.}}){{/list}}"'
expected: '"(1)(2)(3)(4)(5)"'
- name: Implicit Iterator - Decimal
desc: Implicit iterators should cast decimals to strings and interpolate.
data:
list: [ 1.10, 2.20, 3.30, 4.40, 5.50 ]
template: '"{{#list}}({{.}}){{/list}}"'
expected: '"(1.1)(2.2)(3.3)(4.4)(5.5)"'
# Dotted Names
- name: Dotted Names - Truthy
desc: Dotted names should be valid for Section tags.
data: { a: { b: { c: true } } }
template: '"{{#a.b.c}}Here{{/a.b.c}}" == "Here"'
expected: '"Here" == "Here"'
- name: Dotted Names - Falsey
desc: Dotted names should be valid for Section tags.
data: { a: { b: { c: false } } }
template: '"{{#a.b.c}}Here{{/a.b.c}}" == ""'
expected: '"" == ""'
- name: Dotted Names - Broken Chains
desc: Dotted names that cannot be resolved should be considered falsey.
data: { a: { } }
template: '"{{#a.b.c}}Here{{/a.b.c}}" == ""'
expected: '"" == ""'
# Whitespace Sensitivity
- name: Surrounding Whitespace
desc: Sections should not alter surrounding whitespace.
data: { boolean: true }
template: " | {{#boolean}}\t|\t{{/boolean}} | \n"
expected: " | \t|\t | \n"
- name: Internal Whitespace
desc: Sections should not alter internal whitespace.
data: { boolean: true }
template: " | {{#boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n"
expected: " | \n | \n"
- name: Indented Inline Sections
desc: Single-line sections should not alter surrounding whitespace.
data: { boolean: true }
template: " {{#boolean}}YES{{/boolean}}\n {{#boolean}}GOOD{{/boolean}}\n"
expected: " YES\n GOOD\n"
- name: Standalone Lines
desc: Standalone lines should be removed from the template.
data: { boolean: true }
template: |
| This Is
{{#boolean}}
|
{{/boolean}}
| A Line
expected: |
| This Is
|
| A Line
- name: Indented Standalone Lines
desc: Indented standalone lines should be removed from the template.
data: { boolean: true }
template: |
| This Is
{{#boolean}}
|
{{/boolean}}
| A Line
expected: |
| This Is
|
| A Line
- name: Standalone Line Endings
desc: '"\r\n" should be considered a newline for standalone tags.'
data: { boolean: true }
template: "|\r\n{{#boolean}}\r\n{{/boolean}}\r\n|"
expected: "|\r\n|"
- name: Standalone Without Previous Line
desc: Standalone tags should not require a newline to precede them.
data: { boolean: true }
template: " {{#boolean}}\n#{{/boolean}}\n/"
expected: "#\n/"
- name: Standalone Without Newline
desc: Standalone tags should not require a newline to follow them.
data: { boolean: true }
template: "#{{#boolean}}\n/\n {{/boolean}}"
expected: "#\n/\n"
# Whitespace Insensitivity
- name: Padding
desc: Superfluous in-tag whitespace should be ignored.
data: { boolean: true }
template: '|{{# boolean }}={{/ boolean }}|'
expected: '|=|'
whisker/inst/specs/inverted.yml 0000644 0001751 0000144 00000014614 13527765260 016424 0 ustar hornik users overview: |
Inverted Section tags and End Section tags are used in combination to wrap a
section of the template.
These tags' content MUST be a non-whitespace character sequence NOT
containing the current closing delimiter; each Inverted Section tag MUST be
followed by an End Section tag with the same content within the same
section.
This tag's content names the data to replace the tag. Name resolution is as
follows:
1) Split the name on periods; the first part is the name to resolve, any
remaining parts should be retained.
2) Walk the context stack from top to bottom, finding the first context
that is a) a hash containing the name as a key OR b) an object responding
to a method with the given name.
3) If the context is a hash, the data is the value associated with the
name.
4) If the context is an object and the method with the given name has an
arity of 1, the method SHOULD be called with a String containing the
unprocessed contents of the sections; the data is the value returned.
5) Otherwise, the data is the value returned by calling the method with
the given name.
6) If any name parts were retained in step 1, each should be resolved
against a context stack containing only the result from the former
resolution. If any part fails resolution, the result should be considered
falsey, and should interpolate as the empty string.
If the data is not of a list type, it is coerced into a list as follows: if
the data is truthy (e.g. `!!data == true`), use a single-element list
containing the data, otherwise use an empty list.
This section MUST NOT be rendered unless the data list is empty.
Inverted Section and End Section tags SHOULD be treated as standalone when
appropriate.
tests:
- name: Falsey
desc: Falsey sections should have their contents rendered.
data: { boolean: false }
template: '"{{^boolean}}This should be rendered.{{/boolean}}"'
expected: '"This should be rendered."'
- name: Truthy
desc: Truthy sections should have their contents omitted.
data: { boolean: true }
template: '"{{^boolean}}This should not be rendered.{{/boolean}}"'
expected: '""'
- name: Context
desc: Objects and hashes should behave like truthy values.
data: { context: { name: 'Joe' } }
template: '"{{^context}}Hi {{name}}.{{/context}}"'
expected: '""'
- name: List
desc: Lists should behave like truthy values.
data: { list: [ { n: 1 }, { n: 2 }, { n: 3 } ] }
template: '"{{^list}}{{n}}{{/list}}"'
expected: '""'
- name: Empty List
desc: Empty lists should behave like falsey values.
data: { list: [ ] }
template: '"{{^list}}Yay lists!{{/list}}"'
expected: '"Yay lists!"'
- name: Doubled
desc: Multiple inverted sections per template should be permitted.
data: { bool: false, two: 'second' }
template: |
{{^bool}}
* first
{{/bool}}
* {{two}}
{{^bool}}
* third
{{/bool}}
expected: |
* first
* second
* third
- name: Nested (Falsey)
desc: Nested falsey sections should have their contents rendered.
data: { bool: false }
template: "| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |"
expected: "| A B C D E |"
- name: Nested (Truthy)
desc: Nested truthy sections should be omitted.
data: { bool: true }
template: "| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |"
expected: "| A E |"
- name: Context Misses
desc: Failed context lookups should be considered falsey.
data: { }
template: "[{{^missing}}Cannot find key 'missing'!{{/missing}}]"
expected: "[Cannot find key 'missing'!]"
# Dotted Names
- name: Dotted Names - Truthy
desc: Dotted names should be valid for Inverted Section tags.
data: { a: { b: { c: true } } }
template: '"{{^a.b.c}}Not Here{{/a.b.c}}" == ""'
expected: '"" == ""'
- name: Dotted Names - Falsey
desc: Dotted names should be valid for Inverted Section tags.
data: { a: { b: { c: false } } }
template: '"{{^a.b.c}}Not Here{{/a.b.c}}" == "Not Here"'
expected: '"Not Here" == "Not Here"'
- name: Dotted Names - Broken Chains
desc: Dotted names that cannot be resolved should be considered falsey.
data: { a: { } }
template: '"{{^a.b.c}}Not Here{{/a.b.c}}" == "Not Here"'
expected: '"Not Here" == "Not Here"'
# Whitespace Sensitivity
- name: Surrounding Whitespace
desc: Inverted sections should not alter surrounding whitespace.
data: { boolean: false }
template: " | {{^boolean}}\t|\t{{/boolean}} | \n"
expected: " | \t|\t | \n"
- name: Internal Whitespace
desc: Inverted should not alter internal whitespace.
data: { boolean: false }
template: " | {{^boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n"
expected: " | \n | \n"
- name: Indented Inline Sections
desc: Single-line sections should not alter surrounding whitespace.
data: { boolean: false }
template: " {{^boolean}}NO{{/boolean}}\n {{^boolean}}WAY{{/boolean}}\n"
expected: " NO\n WAY\n"
- name: Standalone Lines
desc: Standalone lines should be removed from the template.
data: { boolean: false }
template: |
| This Is
{{^boolean}}
|
{{/boolean}}
| A Line
expected: |
| This Is
|
| A Line
- name: Standalone Indented Lines
desc: Standalone indented lines should be removed from the template.
data: { boolean: false }
template: |
| This Is
{{^boolean}}
|
{{/boolean}}
| A Line
expected: |
| This Is
|
| A Line
- name: Standalone Line Endings
desc: '"\r\n" should be considered a newline for standalone tags.'
data: { boolean: false }
template: "|\r\n{{^boolean}}\r\n{{/boolean}}\r\n|"
expected: "|\r\n|"
- name: Standalone Without Previous Line
desc: Standalone tags should not require a newline to precede them.
data: { boolean: false }
template: " {{^boolean}}\n^{{/boolean}}\n/"
expected: "^\n/"
- name: Standalone Without Newline
desc: Standalone tags should not require a newline to follow them.
data: { boolean: false }
template: "^{{^boolean}}\n/\n {{/boolean}}"
expected: "^\n/\n"
# Whitespace Insensitivity
- name: Padding
desc: Superfluous in-tag whitespace should be ignored.
data: { boolean: false }
template: '|{{^ boolean }}={{/ boolean }}|'
expected: '|=|'
whisker/inst/specs/inverted.json 0000644 0001751 0000144 00000014073 13527765260 016573 0 ustar hornik users {"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Inverted Section tags and End Section tags are used in combination to wrap a\nsection of the template.\n\nThese tags' content MUST be a non-whitespace character sequence NOT\ncontaining the current closing delimiter; each Inverted Section tag MUST be\nfollowed by an End Section tag with the same content within the same\nsection.\n\nThis tag's content names the data to replace the tag. Name resolution is as\nfollows:\n 1) Split the name on periods; the first part is the name to resolve, any\n remaining parts should be retained.\n 2) Walk the context stack from top to bottom, finding the first context\n that is a) a hash containing the name as a key OR b) an object responding\n to a method with the given name.\n 3) If the context is a hash, the data is the value associated with the\n name.\n 4) If the context is an object and the method with the given name has an\n arity of 1, the method SHOULD be called with a String containing the\n unprocessed contents of the sections; the data is the value returned.\n 5) Otherwise, the data is the value returned by calling the method with\n the given name.\n 6) If any name parts were retained in step 1, each should be resolved\n against a context stack containing only the result from the former\n resolution. If any part fails resolution, the result should be considered\n falsey, and should interpolate as the empty string.\nIf the data is not of a list type, it is coerced into a list as follows: if\nthe data is truthy (e.g. `!!data == true`), use a single-element list\ncontaining the data, otherwise use an empty list.\n\nThis section MUST NOT be rendered unless the data list is empty.\n\nInverted Section and End Section tags SHOULD be treated as standalone when\nappropriate.\n","tests":[{"name":"Falsey","data":{"boolean":false},"expected":"\"This should be rendered.\"","template":"\"{{^boolean}}This should be rendered.{{/boolean}}\"","desc":"Falsey sections should have their contents rendered."},{"name":"Truthy","data":{"boolean":true},"expected":"\"\"","template":"\"{{^boolean}}This should not be rendered.{{/boolean}}\"","desc":"Truthy sections should have their contents omitted."},{"name":"Context","data":{"context":{"name":"Joe"}},"expected":"\"\"","template":"\"{{^context}}Hi {{name}}.{{/context}}\"","desc":"Objects and hashes should behave like truthy values."},{"name":"List","data":{"list":[{"n":1},{"n":2},{"n":3}]},"expected":"\"\"","template":"\"{{^list}}{{n}}{{/list}}\"","desc":"Lists should behave like truthy values."},{"name":"Empty List","data":{"list":[]},"expected":"\"Yay lists!\"","template":"\"{{^list}}Yay lists!{{/list}}\"","desc":"Empty lists should behave like falsey values."},{"name":"Doubled","data":{"two":"second","bool":false},"expected":"* first\n* second\n* third\n","template":"{{^bool}}\n* first\n{{/bool}}\n* {{two}}\n{{^bool}}\n* third\n{{/bool}}\n","desc":"Multiple inverted sections per template should be permitted."},{"name":"Nested (Falsey)","data":{"bool":false},"expected":"| A B C D E |","template":"| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |","desc":"Nested falsey sections should have their contents rendered."},{"name":"Nested (Truthy)","data":{"bool":true},"expected":"| A E |","template":"| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |","desc":"Nested truthy sections should be omitted."},{"name":"Context Misses","data":{},"expected":"[Cannot find key 'missing'!]","template":"[{{^missing}}Cannot find key 'missing'!{{/missing}}]","desc":"Failed context lookups should be considered falsey."},{"name":"Dotted Names - Truthy","data":{"a":{"b":{"c":true}}},"expected":"\"\" == \"\"","template":"\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"\"","desc":"Dotted names should be valid for Inverted Section tags."},{"name":"Dotted Names - Falsey","data":{"a":{"b":{"c":false}}},"expected":"\"Not Here\" == \"Not Here\"","template":"\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\"","desc":"Dotted names should be valid for Inverted Section tags."},{"name":"Dotted Names - Broken Chains","data":{"a":{}},"expected":"\"Not Here\" == \"Not Here\"","template":"\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\"","desc":"Dotted names that cannot be resolved should be considered falsey."},{"name":"Surrounding Whitespace","data":{"boolean":false},"expected":" | \t|\t | \n","template":" | {{^boolean}}\t|\t{{/boolean}} | \n","desc":"Inverted sections should not alter surrounding whitespace."},{"name":"Internal Whitespace","data":{"boolean":false},"expected":" | \n | \n","template":" | {{^boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n","desc":"Inverted should not alter internal whitespace."},{"name":"Indented Inline Sections","data":{"boolean":false},"expected":" NO\n WAY\n","template":" {{^boolean}}NO{{/boolean}}\n {{^boolean}}WAY{{/boolean}}\n","desc":"Single-line sections should not alter surrounding whitespace."},{"name":"Standalone Lines","data":{"boolean":false},"expected":"| This Is\n|\n| A Line\n","template":"| This Is\n{{^boolean}}\n|\n{{/boolean}}\n| A Line\n","desc":"Standalone lines should be removed from the template."},{"name":"Standalone Indented Lines","data":{"boolean":false},"expected":"| This Is\n|\n| A Line\n","template":"| This Is\n {{^boolean}}\n|\n {{/boolean}}\n| A Line\n","desc":"Standalone indented lines should be removed from the template."},{"name":"Standalone Line Endings","data":{"boolean":false},"expected":"|\r\n|","template":"|\r\n{{^boolean}}\r\n{{/boolean}}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags."},{"name":"Standalone Without Previous Line","data":{"boolean":false},"expected":"^\n/","template":" {{^boolean}}\n^{{/boolean}}\n/","desc":"Standalone tags should not require a newline to precede them."},{"name":"Standalone Without Newline","data":{"boolean":false},"expected":"^\n/\n","template":"^{{^boolean}}\n/\n {{/boolean}}","desc":"Standalone tags should not require a newline to follow them."},{"name":"Padding","data":{"boolean":false},"expected":"|=|","template":"|{{^ boolean }}={{/ boolean }}|","desc":"Superfluous in-tag whitespace should be ignored."}]} whisker/inst/specs/delimiters.json 0000644 0001751 0000144 00000006527 13527765260 017121 0 ustar hornik users {"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Set Delimiter tags are used to change the tag delimiters for all content\nfollowing the tag in the current compilation unit.\n\nThe tag's content MUST be any two non-whitespace sequences (separated by\nwhitespace) EXCEPT an equals sign ('=') followed by the current closing\ndelimiter.\n\nSet Delimiter tags SHOULD be treated as standalone when appropriate.\n","tests":[{"name":"Pair Behavior","data":{"text":"Hey!"},"expected":"(Hey!)","template":"{{=<% %>=}}(<%text%>)","desc":"The equals sign (used on both sides) should permit delimiter changes."},{"name":"Special Characters","data":{"text":"It worked!"},"expected":"(It worked!)","template":"({{=[ ]=}}[text])","desc":"Characters with special meaning regexen should be valid delimiters."},{"name":"Sections","data":{"section":true,"data":"I got interpolated."},"expected":"[\n I got interpolated.\n |data|\n\n {{data}}\n I got interpolated.\n]\n","template":"[\n{{#section}}\n {{data}}\n |data|\n{{/section}}\n\n{{= | | =}}\n|#section|\n {{data}}\n |data|\n|/section|\n]\n","desc":"Delimiters set outside sections should persist."},{"name":"Inverted Sections","data":{"section":false,"data":"I got interpolated."},"expected":"[\n I got interpolated.\n |data|\n\n {{data}}\n I got interpolated.\n]\n","template":"[\n{{^section}}\n {{data}}\n |data|\n{{/section}}\n\n{{= | | =}}\n|^section|\n {{data}}\n |data|\n|/section|\n]\n","desc":"Delimiters set outside inverted sections should persist."},{"name":"Partial Inheritence","data":{"value":"yes"},"expected":"[ .yes. ]\n[ .yes. ]\n","template":"[ {{>include}} ]\n{{= | | =}}\n[ |>include| ]\n","desc":"Delimiters set in a parent template should not affect a partial.","partials":{"include":".{{value}}."}},{"name":"Post-Partial Behavior","data":{"value":"yes"},"expected":"[ .yes. .yes. ]\n[ .yes. .|value|. ]\n","template":"[ {{>include}} ]\n[ .{{value}}. .|value|. ]\n","desc":"Delimiters set in a partial should not affect the parent template.","partials":{"include":".{{value}}. {{= | | =}} .|value|."}},{"name":"Surrounding Whitespace","data":{},"expected":"| |","template":"| {{=@ @=}} |","desc":"Surrounding whitespace should be left untouched."},{"name":"Outlying Whitespace (Inline)","data":{},"expected":" | \n","template":" | {{=@ @=}}\n","desc":"Whitespace should be left untouched."},{"name":"Standalone Tag","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n{{=@ @=}}\nEnd.\n","desc":"Standalone lines should be removed from the template."},{"name":"Indented Standalone Tag","data":{},"expected":"Begin.\nEnd.\n","template":"Begin.\n {{=@ @=}}\nEnd.\n","desc":"Indented standalone lines should be removed from the template."},{"name":"Standalone Line Endings","data":{},"expected":"|\r\n|","template":"|\r\n{{= @ @ =}}\r\n|","desc":"\"\\r\\n\" should be considered a newline for standalone tags."},{"name":"Standalone Without Previous Line","data":{},"expected":"=","template":" {{=@ @=}}\n=","desc":"Standalone tags should not require a newline to precede them."},{"name":"Standalone Without Newline","data":{},"expected":"=\n","template":"=\n {{=@ @=}}","desc":"Standalone tags should not require a newline to follow them."},{"name":"Pair with Padding","data":{},"expected":"||","template":"|{{= @ @ =}}|","desc":"Superfluous in-tag whitespace should be ignored."}]} whisker/inst/specs/delimiters.yml 0000644 0001751 0000144 00000007332 13527765260 016744 0 ustar hornik users overview: |
Set Delimiter tags are used to change the tag delimiters for all content
following the tag in the current compilation unit.
The tag's content MUST be any two non-whitespace sequences (separated by
whitespace) EXCEPT an equals sign ('=') followed by the current closing
delimiter.
Set Delimiter tags SHOULD be treated as standalone when appropriate.
tests:
- name: Pair Behavior
desc: The equals sign (used on both sides) should permit delimiter changes.
data: { text: 'Hey!' }
template: '{{=<% %>=}}(<%text%>)'
expected: '(Hey!)'
- name: Special Characters
desc: Characters with special meaning regexen should be valid delimiters.
data: { text: 'It worked!' }
template: '({{=[ ]=}}[text])'
expected: '(It worked!)'
- name: Sections
desc: Delimiters set outside sections should persist.
data: { section: true, data: 'I got interpolated.' }
template: |
[
{{#section}}
{{data}}
|data|
{{/section}}
{{= | | =}}
|#section|
{{data}}
|data|
|/section|
]
expected: |
[
I got interpolated.
|data|
{{data}}
I got interpolated.
]
- name: Inverted Sections
desc: Delimiters set outside inverted sections should persist.
data: { section: false, data: 'I got interpolated.' }
template: |
[
{{^section}}
{{data}}
|data|
{{/section}}
{{= | | =}}
|^section|
{{data}}
|data|
|/section|
]
expected: |
[
I got interpolated.
|data|
{{data}}
I got interpolated.
]
- name: Partial Inheritence
desc: Delimiters set in a parent template should not affect a partial.
data: { value: 'yes' }
partials:
include: '.{{value}}.'
template: |
[ {{>include}} ]
{{= | | =}}
[ |>include| ]
expected: |
[ .yes. ]
[ .yes. ]
- name: Post-Partial Behavior
desc: Delimiters set in a partial should not affect the parent template.
data: { value: 'yes' }
partials:
include: '.{{value}}. {{= | | =}} .|value|.'
template: |
[ {{>include}} ]
[ .{{value}}. .|value|. ]
expected: |
[ .yes. .yes. ]
[ .yes. .|value|. ]
# Whitespace Sensitivity
- name: Surrounding Whitespace
desc: Surrounding whitespace should be left untouched.
data: { }
template: '| {{=@ @=}} |'
expected: '| |'
- name: Outlying Whitespace (Inline)
desc: Whitespace should be left untouched.
data: { }
template: " | {{=@ @=}}\n"
expected: " | \n"
- name: Standalone Tag
desc: Standalone lines should be removed from the template.
data: { }
template: |
Begin.
{{=@ @=}}
End.
expected: |
Begin.
End.
- name: Indented Standalone Tag
desc: Indented standalone lines should be removed from the template.
data: { }
template: |
Begin.
{{=@ @=}}
End.
expected: |
Begin.
End.
- name: Standalone Line Endings
desc: '"\r\n" should be considered a newline for standalone tags.'
data: { }
template: "|\r\n{{= @ @ =}}\r\n|"
expected: "|\r\n|"
- name: Standalone Without Previous Line
desc: Standalone tags should not require a newline to precede them.
data: { }
template: " {{=@ @=}}\n="
expected: "="
- name: Standalone Without Newline
desc: Standalone tags should not require a newline to follow them.
data: { }
template: "=\n {{=@ @=}}"
expected: "=\n"
# Whitespace Insensitivity
- name: Pair with Padding
desc: Superfluous in-tag whitespace should be ignored.
data: { }
template: '|{{= @ @ =}}|'
expected: '||'
whisker/inst/specs/interpolation.json 0000644 0001751 0000144 00000017064 13527765260 017645 0 ustar hornik users {"__ATTN__":"Do not edit this file; changes belong in the appropriate YAML file.","overview":"Interpolation tags are used to integrate dynamic content into the template.\n\nThe tag's content MUST be a non-whitespace character sequence NOT containing\nthe current closing delimiter.\n\nThis tag's content names the data to replace the tag. A single period (`.`)\nindicates that the item currently sitting atop the context stack should be\nused; otherwise, name resolution is as follows:\n 1) Split the name on periods; the first part is the name to resolve, any\n remaining parts should be retained.\n 2) Walk the context stack from top to bottom, finding the first context\n that is a) a hash containing the name as a key OR b) an object responding\n to a method with the given name.\n 3) If the context is a hash, the data is the value associated with the\n name.\n 4) If the context is an object, the data is the value returned by the\n method with the given name.\n 5) If any name parts were retained in step 1, each should be resolved\n against a context stack containing only the result from the former\n resolution. If any part fails resolution, the result should be considered\n falsey, and should interpolate as the empty string.\nData should be coerced into a string (and escaped, if appropriate) before\ninterpolation.\n\nThe Interpolation tags MUST NOT be treated as standalone.\n","tests":[{"name":"No Interpolation","data":{},"expected":"Hello from {Mustache}!\n","template":"Hello from {Mustache}!\n","desc":"Mustache-free templates should render as-is."},{"name":"Basic Interpolation","data":{"subject":"world"},"expected":"Hello, world!\n","template":"Hello, {{subject}}!\n","desc":"Unadorned tags should interpolate content into the template."},{"name":"HTML Escaping","data":{"forbidden":"& \" < >"},"expected":"These characters should be HTML escaped: & " < >\n","template":"These characters should be HTML escaped: {{forbidden}}\n","desc":"Basic interpolation should be HTML escaped."},{"name":"Triple Mustache","data":{"forbidden":"& \" < >"},"expected":"These characters should not be HTML escaped: & \" < >\n","template":"These characters should not be HTML escaped: {{{forbidden}}}\n","desc":"Triple mustaches should interpolate without HTML escaping."},{"name":"Ampersand","data":{"forbidden":"& \" < >"},"expected":"These characters should not be HTML escaped: & \" < >\n","template":"These characters should not be HTML escaped: {{&forbidden}}\n","desc":"Ampersand should interpolate without HTML escaping."},{"name":"Basic Integer Interpolation","data":{"mph":85},"expected":"\"85 miles an hour!\"","template":"\"{{mph}} miles an hour!\"","desc":"Integers should interpolate seamlessly."},{"name":"Triple Mustache Integer Interpolation","data":{"mph":85},"expected":"\"85 miles an hour!\"","template":"\"{{{mph}}} miles an hour!\"","desc":"Integers should interpolate seamlessly."},{"name":"Ampersand Integer Interpolation","data":{"mph":85},"expected":"\"85 miles an hour!\"","template":"\"{{&mph}} miles an hour!\"","desc":"Integers should interpolate seamlessly."},{"name":"Basic Decimal Interpolation","data":{"power":1.21},"expected":"\"1.21 jiggawatts!\"","template":"\"{{power}} jiggawatts!\"","desc":"Decimals should interpolate seamlessly with proper significance."},{"name":"Triple Mustache Decimal Interpolation","data":{"power":1.21},"expected":"\"1.21 jiggawatts!\"","template":"\"{{{power}}} jiggawatts!\"","desc":"Decimals should interpolate seamlessly with proper significance."},{"name":"Ampersand Decimal Interpolation","data":{"power":1.21},"expected":"\"1.21 jiggawatts!\"","template":"\"{{&power}} jiggawatts!\"","desc":"Decimals should interpolate seamlessly with proper significance."},{"name":"Basic Context Miss Interpolation","data":{},"expected":"I () be seen!","template":"I ({{cannot}}) be seen!","desc":"Failed context lookups should default to empty strings."},{"name":"Triple Mustache Context Miss Interpolation","data":{},"expected":"I () be seen!","template":"I ({{{cannot}}}) be seen!","desc":"Failed context lookups should default to empty strings."},{"name":"Ampersand Context Miss Interpolation","data":{},"expected":"I () be seen!","template":"I ({{&cannot}}) be seen!","desc":"Failed context lookups should default to empty strings."},{"name":"Dotted Names - Basic Interpolation","data":{"person":{"name":"Joe"}},"expected":"\"Joe\" == \"Joe\"","template":"\"{{person.name}}\" == \"{{#person}}{{name}}{{/person}}\"","desc":"Dotted names should be considered a form of shorthand for sections."},{"name":"Dotted Names - Triple Mustache Interpolation","data":{"person":{"name":"Joe"}},"expected":"\"Joe\" == \"Joe\"","template":"\"{{{person.name}}}\" == \"{{#person}}{{{name}}}{{/person}}\"","desc":"Dotted names should be considered a form of shorthand for sections."},{"name":"Dotted Names - Ampersand Interpolation","data":{"person":{"name":"Joe"}},"expected":"\"Joe\" == \"Joe\"","template":"\"{{&person.name}}\" == \"{{#person}}{{&name}}{{/person}}\"","desc":"Dotted names should be considered a form of shorthand for sections."},{"name":"Dotted Names - Arbitrary Depth","data":{"a":{"b":{"c":{"d":{"e":{"name":"Phil"}}}}}},"expected":"\"Phil\" == \"Phil\"","template":"\"{{a.b.c.d.e.name}}\" == \"Phil\"","desc":"Dotted names should be functional to any level of nesting."},{"name":"Dotted Names - Broken Chains","data":{"a":{}},"expected":"\"\" == \"\"","template":"\"{{a.b.c}}\" == \"\"","desc":"Any falsey value prior to the last part of the name should yield ''."},{"name":"Dotted Names - Broken Chain Resolution","data":{"a":{"b":{}},"c":{"name":"Jim"}},"expected":"\"\" == \"\"","template":"\"{{a.b.c.name}}\" == \"\"","desc":"Each part of a dotted name should resolve only against its parent."},{"name":"Dotted Names - Initial Resolution","data":{"a":{"b":{"c":{"d":{"e":{"name":"Phil"}}}}},"b":{"c":{"d":{"e":{"name":"Wrong"}}}}},"expected":"\"Phil\" == \"Phil\"","template":"\"{{#a}}{{b.c.d.e.name}}{{/a}}\" == \"Phil\"","desc":"The first part of a dotted name should resolve as any other name."},{"name":"Interpolation - Surrounding Whitespace","data":{"string":"---"},"expected":"| --- |","template":"| {{string}} |","desc":"Interpolation should not alter surrounding whitespace."},{"name":"Triple Mustache - Surrounding Whitespace","data":{"string":"---"},"expected":"| --- |","template":"| {{{string}}} |","desc":"Interpolation should not alter surrounding whitespace."},{"name":"Ampersand - Surrounding Whitespace","data":{"string":"---"},"expected":"| --- |","template":"| {{&string}} |","desc":"Interpolation should not alter surrounding whitespace."},{"name":"Interpolation - Standalone","data":{"string":"---"},"expected":" ---\n","template":" {{string}}\n","desc":"Standalone interpolation should not alter surrounding whitespace."},{"name":"Triple Mustache - Standalone","data":{"string":"---"},"expected":" ---\n","template":" {{{string}}}\n","desc":"Standalone interpolation should not alter surrounding whitespace."},{"name":"Ampersand - Standalone","data":{"string":"---"},"expected":" ---\n","template":" {{&string}}\n","desc":"Standalone interpolation should not alter surrounding whitespace."},{"name":"Interpolation With Padding","data":{"string":"---"},"expected":"|---|","template":"|{{ string }}|","desc":"Superfluous in-tag whitespace should be ignored."},{"name":"Triple Mustache With Padding","data":{"string":"---"},"expected":"|---|","template":"|{{{ string }}}|","desc":"Superfluous in-tag whitespace should be ignored."},{"name":"Ampersand With Padding","data":{"string":"---"},"expected":"|---|","template":"|{{& string }}|","desc":"Superfluous in-tag whitespace should be ignored."}]} whisker/inst/tests/ 0000755 0001751 0000144 00000000000 13527765260 014100 5 ustar hornik users whisker/inst/tests/testsections.R 0000644 0001751 0000144 00000026656 13527765260 016771 0 ustar hornik users # Automatically generated from specification file: 'sections.json'
#
# Section tags and End Section tags are used in combination to wrap a section
# of the template for iteration
#
# These tags' content MUST be a non-whitespace character sequence NOT
# containing the current closing delimiter; each Section tag MUST be followed
# by an End Section tag with the same content within the same section.
#
# This tag's content names the data to replace the tag. Name resolution is as
# follows:
# 1) Split the name on periods; the first part is the name to resolve, any
# remaining parts should be retained.
# 2) Walk the context stack from top to bottom, finding the first context
# that is a) a hash containing the name as a key OR b) an object responding
# to a method with the given name.
# 3) If the context is a hash, the data is the value associated with the
# name.
# 4) If the context is an object and the method with the given name has an
# arity of 1, the method SHOULD be called with a String containing the
# unprocessed contents of the sections; the data is the value returned.
# 5) Otherwise, the data is the value returned by calling the method with
# the given name.
# 6) If any name parts were retained in step 1, each should be resolved
# against a context stack containing only the result from the former
# resolution. If any part fails resolution, the result should be considered
# falsey, and should interpolate as the empty string.
# If the data is not of a list type, it is coerced into a list as follows: if
# the data is truthy (e.g. `!!data == true`), use a single-element list
# containing the data, otherwise use an empty list.
#
# For each element in the data list, the element MUST be pushed onto the
# context stack, the section MUST be rendered, and the element MUST be popped
# off the context stack.
#
# Section and End Section tags SHOULD be treated as standalone when
# appropriate.
#
library(testthat)
context('Spec v1.1, sections')
test_that( "Truthy", {
#"Truthy sections should have their contents rendered."
template <- "\"{{#boolean}}This should be rendered.{{/boolean}}\""
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "\"This should be rendered.\"", label=deparse(str), info="Truthy sections should have their contents rendered.")
})
test_that( "Falsey", {
#"Falsey sections should have their contents omitted."
template <- "\"{{#boolean}}This should not be rendered.{{/boolean}}\""
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "\"\"", label=deparse(str), info="Falsey sections should have their contents omitted.")
})
test_that( "Context", {
#"Objects and hashes should be pushed onto the context stack."
template <- "\"{{#context}}Hi {{name}}.{{/context}}\""
data <- list(context = list(name = "Joe"))
str <- whisker.render(template, data=data)
expect_equal(str, "\"Hi Joe.\"", label=deparse(str), info="Objects and hashes should be pushed onto the context stack.")
})
test_that( "Deeply Nested Contexts", {
#"All elements on the context stack should be accessible."
template <- "{{#a}}\n{{one}}\n{{#b}}\n{{one}}{{two}}{{one}}\n{{#c}}\n{{one}}{{two}}{{three}}{{two}}{{one}}\n{{#d}}\n{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}\n{{#e}}\n{{one}}{{two}}{{three}}{{four}}{{five}}{{four}}{{three}}{{two}}{{one}}\n{{/e}}\n{{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}}\n{{/d}}\n{{one}}{{two}}{{three}}{{two}}{{one}}\n{{/c}}\n{{one}}{{two}}{{one}}\n{{/b}}\n{{one}}\n{{/a}}\n"
data <- list(a = list(one = 1), b = list(two = 2), c = list(three = 3),
d = list(four = 4), e = list(five = 5))
str <- whisker.render(template, data=data)
expect_equal(str, "1\n121\n12321\n1234321\n123454321\n1234321\n12321\n121\n1\n", label=deparse(str), info="All elements on the context stack should be accessible.")
})
test_that( "List", {
#"Lists should be iterated; list items should visit the context stack."
template <- "\"{{#list}}{{item}}{{/list}}\""
data <- list(list = list(list(item = 1), list(item = 2), list(item = 3)))
str <- whisker.render(template, data=data)
expect_equal(str, "\"123\"", label=deparse(str), info="Lists should be iterated; list items should visit the context stack.")
})
test_that( "Empty List", {
#"Empty lists should behave like falsey values."
template <- "\"{{#list}}Yay lists!{{/list}}\""
data <- list(list = list())
str <- whisker.render(template, data=data)
expect_equal(str, "\"\"", label=deparse(str), info="Empty lists should behave like falsey values.")
})
test_that( "Doubled", {
#"Multiple sections per template should be permitted."
template <- "{{#bool}}\n* first\n{{/bool}}\n* {{two}}\n{{#bool}}\n* third\n{{/bool}}\n"
data <- list(two = "second", bool = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "* first\n* second\n* third\n", label=deparse(str), info="Multiple sections per template should be permitted.")
})
test_that( "Nested (Truthy)", {
#"Nested truthy sections should have their contents rendered."
template <- "| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |"
data <- list(bool = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "| A B C D E |", label=deparse(str), info="Nested truthy sections should have their contents rendered.")
})
test_that( "Nested (Falsey)", {
#"Nested falsey sections should be omitted."
template <- "| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |"
data <- list(bool = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "| A E |", label=deparse(str), info="Nested falsey sections should be omitted.")
})
test_that( "Context Misses", {
#"Failed context lookups should be considered falsey."
template <- "[{{#missing}}Found key 'missing'!{{/missing}}]"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "[]", label=deparse(str), info="Failed context lookups should be considered falsey.")
})
test_that( "Implicit Iterator - String", {
#"Implicit iterators should directly interpolate strings."
template <- "\"{{#list}}({{.}}){{/list}}\""
data <- list(list = c("a", "b", "c", "d", "e"))
str <- whisker.render(template, data=data)
expect_equal(str, "\"(a)(b)(c)(d)(e)\"", label=deparse(str), info="Implicit iterators should directly interpolate strings.")
})
test_that( "Implicit Iterator - Integer", {
#"Implicit iterators should cast integers to strings and interpolate."
template <- "\"{{#list}}({{.}}){{/list}}\""
data <- list(list = c(1, 2, 3, 4, 5))
str <- whisker.render(template, data=data)
expect_equal(str, "\"(1)(2)(3)(4)(5)\"", label=deparse(str), info="Implicit iterators should cast integers to strings and interpolate.")
})
test_that( "Implicit Iterator - Decimal", {
#"Implicit iterators should cast decimals to strings and interpolate."
template <- "\"{{#list}}({{.}}){{/list}}\""
data <- list(list = c(1.1, 2.2, 3.3, 4.4, 5.5))
str <- whisker.render(template, data=data)
expect_equal(str, "\"(1.1)(2.2)(3.3)(4.4)(5.5)\"", label=deparse(str), info="Implicit iterators should cast decimals to strings and interpolate.")
})
test_that( "Dotted Names - Truthy", {
#"Dotted names should be valid for Section tags."
template <- "\"{{#a.b.c}}Here{{/a.b.c}}\" == \"Here\""
data <- list(a = list(b = list(c = TRUE)))
str <- whisker.render(template, data=data)
expect_equal(str, "\"Here\" == \"Here\"", label=deparse(str), info="Dotted names should be valid for Section tags.")
})
test_that( "Dotted Names - Falsey", {
#"Dotted names should be valid for Section tags."
template <- "\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\""
data <- list(a = list(b = list(c = FALSE)))
str <- whisker.render(template, data=data)
expect_equal(str, "\"\" == \"\"", label=deparse(str), info="Dotted names should be valid for Section tags.")
})
test_that( "Dotted Names - Broken Chains", {
#"Dotted names that cannot be resolved should be considered falsey."
template <- "\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\""
data <- list(a = list())
str <- whisker.render(template, data=data)
expect_equal(str, "\"\" == \"\"", label=deparse(str), info="Dotted names that cannot be resolved should be considered falsey.")
})
test_that( "Surrounding Whitespace", {
#"Sections should not alter surrounding whitespace."
template <- " | {{#boolean}}\t|\t{{/boolean}} | \n"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, " | \t|\t | \n", label=deparse(str), info="Sections should not alter surrounding whitespace.")
})
test_that( "Internal Whitespace", {
#"Sections should not alter internal whitespace."
template <- " | {{#boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, " | \n | \n", label=deparse(str), info="Sections should not alter internal whitespace.")
})
test_that( "Indented Inline Sections", {
#"Single-line sections should not alter surrounding whitespace."
template <- " {{#boolean}}YES{{/boolean}}\n {{#boolean}}GOOD{{/boolean}}\n"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, " YES\n GOOD\n", label=deparse(str), info="Single-line sections should not alter surrounding whitespace.")
})
test_that( "Standalone Lines", {
#"Standalone lines should be removed from the template."
template <- "| This Is\n{{#boolean}}\n|\n{{/boolean}}\n| A Line\n"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "| This Is\n|\n| A Line\n", label=deparse(str), info="Standalone lines should be removed from the template.")
})
test_that( "Indented Standalone Lines", {
#"Indented standalone lines should be removed from the template."
template <- "| This Is\n {{#boolean}}\n|\n {{/boolean}}\n| A Line\n"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "| This Is\n|\n| A Line\n", label=deparse(str), info="Indented standalone lines should be removed from the template.")
})
test_that( "Standalone Line Endings", {
#"\"\\r\\n\" should be considered a newline for standalone tags."
template <- "|\r\n{{#boolean}}\r\n{{/boolean}}\r\n|"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "|\r\n|", label=deparse(str), info="\"\\r\\n\" should be considered a newline for standalone tags.")
})
test_that( "Standalone Without Previous Line", {
#"Standalone tags should not require a newline to precede them."
template <- " {{#boolean}}\n#{{/boolean}}\n/"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "#\n/", label=deparse(str), info="Standalone tags should not require a newline to precede them.")
})
test_that( "Standalone Without Newline", {
#"Standalone tags should not require a newline to follow them."
template <- "#{{#boolean}}\n/\n {{/boolean}}"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "#\n/\n", label=deparse(str), info="Standalone tags should not require a newline to follow them.")
})
test_that( "Padding", {
#"Superfluous in-tag whitespace should be ignored."
template <- "|{{# boolean }}={{/ boolean }}|"
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "|=|", label=deparse(str), info="Superfluous in-tag whitespace should be ignored.")
})
whisker/inst/tests/testdelimiters.R 0000644 0001751 0000144 00000013166 13527765260 017273 0 ustar hornik users # Automatically generated from specification file: 'delimiters.json'
#
# Set Delimiter tags are used to change the tag delimiters for all content
# following the tag in the current compilation unit.
#
# The tag's content MUST be any two non-whitespace sequences (separated by
# whitespace) EXCEPT an equals sign ('=') followed by the current closing
# delimiter.
#
# Set Delimiter tags SHOULD be treated as standalone when appropriate.
#
library(testthat)
context('Spec v1.1, delimiters')
test_that( "Pair Behavior", {
#"The equals sign (used on both sides) should permit delimiter changes."
template <- "{{=<% %>=}}(<%text%>)"
data <- list(text = "Hey!")
str <- whisker.render(template, data=data)
expect_equal(str, "(Hey!)", label=deparse(str), info="The equals sign (used on both sides) should permit delimiter changes.")
})
test_that( "Special Characters", {
#"Characters with special meaning regexen should be valid delimiters."
template <- "({{=[ ]=}}[text])"
data <- list(text = "It worked!")
str <- whisker.render(template, data=data)
expect_equal(str, "(It worked!)", label=deparse(str), info="Characters with special meaning regexen should be valid delimiters.")
})
test_that( "Sections", {
#"Delimiters set outside sections should persist."
template <- "[\n{{#section}}\n {{data}}\n |data|\n{{/section}}\n\n{{= | | =}}\n|#section|\n {{data}}\n |data|\n|/section|\n]\n"
data <- list(section = TRUE, data = "I got interpolated.")
str <- whisker.render(template, data=data)
expect_equal(str, "[\n I got interpolated.\n |data|\n\n {{data}}\n I got interpolated.\n]\n", label=deparse(str), info="Delimiters set outside sections should persist.")
})
test_that( "Inverted Sections", {
#"Delimiters set outside inverted sections should persist."
template <- "[\n{{^section}}\n {{data}}\n |data|\n{{/section}}\n\n{{= | | =}}\n|^section|\n {{data}}\n |data|\n|/section|\n]\n"
data <- list(section = FALSE, data = "I got interpolated.")
str <- whisker.render(template, data=data)
expect_equal(str, "[\n I got interpolated.\n |data|\n\n {{data}}\n I got interpolated.\n]\n", label=deparse(str), info="Delimiters set outside inverted sections should persist.")
})
test_that( "Partial Inheritence", {
#"Delimiters set in a parent template should not affect a partial."
template <- "[ {{>include}} ]\n{{= | | =}}\n[ |>include| ]\n"
data <- list(value = "yes")
partials <- list(include = ".{{value}}.")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "[ .yes. ]\n[ .yes. ]\n", label=deparse(str), info="Delimiters set in a parent template should not affect a partial.")
})
test_that( "Post-Partial Behavior", {
#"Delimiters set in a partial should not affect the parent template."
template <- "[ {{>include}} ]\n[ .{{value}}. .|value|. ]\n"
data <- list(value = "yes")
partials <- list(include = ".{{value}}. {{= | | =}} .|value|.")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "[ .yes. .yes. ]\n[ .yes. .|value|. ]\n", label=deparse(str), info="Delimiters set in a partial should not affect the parent template.")
})
test_that( "Surrounding Whitespace", {
#"Surrounding whitespace should be left untouched."
template <- "| {{=@ @=}} |"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "| |", label=deparse(str), info="Surrounding whitespace should be left untouched.")
})
test_that( "Outlying Whitespace (Inline)", {
#"Whitespace should be left untouched."
template <- " | {{=@ @=}}\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, " | \n", label=deparse(str), info="Whitespace should be left untouched.")
})
test_that( "Standalone Tag", {
#"Standalone lines should be removed from the template."
template <- "Begin.\n{{=@ @=}}\nEnd.\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "Begin.\nEnd.\n", label=deparse(str), info="Standalone lines should be removed from the template.")
})
test_that( "Indented Standalone Tag", {
#"Indented standalone lines should be removed from the template."
template <- "Begin.\n {{=@ @=}}\nEnd.\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "Begin.\nEnd.\n", label=deparse(str), info="Indented standalone lines should be removed from the template.")
})
test_that( "Standalone Line Endings", {
#"\"\\r\\n\" should be considered a newline for standalone tags."
template <- "|\r\n{{= @ @ =}}\r\n|"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "|\r\n|", label=deparse(str), info="\"\\r\\n\" should be considered a newline for standalone tags.")
})
test_that( "Standalone Without Previous Line", {
#"Standalone tags should not require a newline to precede them."
template <- " {{=@ @=}}\n="
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "=", label=deparse(str), info="Standalone tags should not require a newline to precede them.")
})
test_that( "Standalone Without Newline", {
#"Standalone tags should not require a newline to follow them."
template <- "=\n {{=@ @=}}"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "=\n", label=deparse(str), info="Standalone tags should not require a newline to follow them.")
})
test_that( "Pair with Padding", {
#"Superfluous in-tag whitespace should be ignored."
template <- "|{{= @ @ =}}|"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "||", label=deparse(str), info="Superfluous in-tag whitespace should be ignored.")
})
whisker/inst/tests/testComments.R 0000644 0001751 0000144 00000007724 13527765260 016722 0 ustar hornik users # Automatically generated from specification file: 'comments.json'
#
# Comment tags represent content that should never appear in the resulting
# output.
#
# The tag's content may contain any substring (including newlines) EXCEPT the
# closing delimiter.
#
# Comment tags SHOULD be treated as standalone when appropriate.
#
library(testthat)
context('Spec v1.1, comments')
test_that( "Inline", {
#"Comment blocks should be removed from the template."
template <- "12345{{! Comment Block! }}67890"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "1234567890", label=deparse(str), info="Comment blocks should be removed from the template.")
})
test_that( "Multiline", {
#"Multiline comments should be permitted."
template <- "12345{{!\n This is a\n multi-line comment...\n}}67890\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "1234567890\n", label=deparse(str), info="Multiline comments should be permitted.")
})
test_that( "Standalone", {
#"All standalone comment lines should be removed."
template <- "Begin.\n{{! Comment Block! }}\nEnd.\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "Begin.\nEnd.\n", label=deparse(str), info="All standalone comment lines should be removed.")
})
test_that( "Indented Standalone", {
#"All standalone comment lines should be removed."
template <- "Begin.\n {{! Indented Comment Block! }}\nEnd.\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "Begin.\nEnd.\n", label=deparse(str), info="All standalone comment lines should be removed.")
})
test_that( "Standalone Line Endings", {
#"\"\\r\\n\" should be considered a newline for standalone tags."
template <- "|\r\n{{! Standalone Comment }}\r\n|"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "|\r\n|", label=deparse(str), info="\"\\r\\n\" should be considered a newline for standalone tags.")
})
test_that( "Standalone Without Previous Line", {
#"Standalone tags should not require a newline to precede them."
template <- " {{! I'm Still Standalone }}\n!"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "!", label=deparse(str), info="Standalone tags should not require a newline to precede them.")
})
test_that( "Standalone Without Newline", {
#"Standalone tags should not require a newline to follow them."
template <- "!\n {{! I'm Still Standalone }}"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "!\n", label=deparse(str), info="Standalone tags should not require a newline to follow them.")
})
test_that( "Multiline Standalone", {
#"All standalone comment lines should be removed."
template <- "Begin.\n{{!\nSomething's going on here...\n}}\nEnd.\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "Begin.\nEnd.\n", label=deparse(str), info="All standalone comment lines should be removed.")
})
test_that( "Indented Multiline Standalone", {
#"All standalone comment lines should be removed."
template <- "Begin.\n {{!\n Something's going on here...\n }}\nEnd.\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "Begin.\nEnd.\n", label=deparse(str), info="All standalone comment lines should be removed.")
})
test_that( "Indented Inline", {
#"Inline comments should not strip whitespace"
template <- " 12 {{! 34 }}\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, " 12 \n", label=deparse(str), info="Inline comments should not strip whitespace")
})
test_that( "Surrounding Whitespace", {
#"Comment removal should preserve surrounding whitespace."
template <- "12345 {{! Comment Block! }} 67890"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "12345 67890", label=deparse(str), info="Comment removal should preserve surrounding whitespace.")
})
whisker/inst/tests/testinterpolation.R 0000644 0001751 0000144 00000032107 13527765260 020015 0 ustar hornik users # Automatically generated from specification file: 'interpolation.json'
#
# Interpolation tags are used to integrate dynamic content into the template.
#
# The tag's content MUST be a non-whitespace character sequence NOT containing
# the current closing delimiter.
#
# This tag's content names the data to replace the tag. A single period (`.`)
# indicates that the item currently sitting atop the context stack should be
# used; otherwise, name resolution is as follows:
# 1) Split the name on periods; the first part is the name to resolve, any
# remaining parts should be retained.
# 2) Walk the context stack from top to bottom, finding the first context
# that is a) a hash containing the name as a key OR b) an object responding
# to a method with the given name.
# 3) If the context is a hash, the data is the value associated with the
# name.
# 4) If the context is an object, the data is the value returned by the
# method with the given name.
# 5) If any name parts were retained in step 1, each should be resolved
# against a context stack containing only the result from the former
# resolution. If any part fails resolution, the result should be considered
# falsey, and should interpolate as the empty string.
# Data should be coerced into a string (and escaped, if appropriate) before
# interpolation.
#
# The Interpolation tags MUST NOT be treated as standalone.
#
library(testthat)
context('Spec v1.1, interpolation')
test_that( "No Interpolation", {
#"Mustache-free templates should render as-is."
template <- "Hello from {Mustache}!\n"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "Hello from {Mustache}!\n", label=deparse(str), info="Mustache-free templates should render as-is.")
})
test_that( "Basic Interpolation", {
#"Unadorned tags should interpolate content into the template."
template <- "Hello, {{subject}}!\n"
data <- list(subject = "world")
str <- whisker.render(template, data=data)
expect_equal(str, "Hello, world!\n", label=deparse(str), info="Unadorned tags should interpolate content into the template.")
})
test_that( "HTML Escaping", {
#"Basic interpolation should be HTML escaped."
template <- "These characters should be HTML escaped: {{forbidden}}\n"
data <- list(forbidden = "& \" < >")
str <- whisker.render(template, data=data)
expect_equal(str, "These characters should be HTML escaped: & " < >\n", label=deparse(str), info="Basic interpolation should be HTML escaped.")
})
test_that( "Triple Mustache", {
#"Triple mustaches should interpolate without HTML escaping."
template <- "These characters should not be HTML escaped: {{{forbidden}}}\n"
data <- list(forbidden = "& \" < >")
str <- whisker.render(template, data=data)
expect_equal(str, "These characters should not be HTML escaped: & \" < >\n", label=deparse(str), info="Triple mustaches should interpolate without HTML escaping.")
})
test_that( "Ampersand", {
#"Ampersand should interpolate without HTML escaping."
template <- "These characters should not be HTML escaped: {{&forbidden}}\n"
data <- list(forbidden = "& \" < >")
str <- whisker.render(template, data=data)
expect_equal(str, "These characters should not be HTML escaped: & \" < >\n", label=deparse(str), info="Ampersand should interpolate without HTML escaping.")
})
test_that( "Basic Integer Interpolation", {
#"Integers should interpolate seamlessly."
template <- "\"{{mph}} miles an hour!\""
data <- list(mph = 85)
str <- whisker.render(template, data=data)
expect_equal(str, "\"85 miles an hour!\"", label=deparse(str), info="Integers should interpolate seamlessly.")
})
test_that( "Triple Mustache Integer Interpolation", {
#"Integers should interpolate seamlessly."
template <- "\"{{{mph}}} miles an hour!\""
data <- list(mph = 85)
str <- whisker.render(template, data=data)
expect_equal(str, "\"85 miles an hour!\"", label=deparse(str), info="Integers should interpolate seamlessly.")
})
test_that( "Ampersand Integer Interpolation", {
#"Integers should interpolate seamlessly."
template <- "\"{{&mph}} miles an hour!\""
data <- list(mph = 85)
str <- whisker.render(template, data=data)
expect_equal(str, "\"85 miles an hour!\"", label=deparse(str), info="Integers should interpolate seamlessly.")
})
test_that( "Basic Decimal Interpolation", {
#"Decimals should interpolate seamlessly with proper significance."
template <- "\"{{power}} jiggawatts!\""
data <- list(power = 1.21)
str <- whisker.render(template, data=data)
expect_equal(str, "\"1.21 jiggawatts!\"", label=deparse(str), info="Decimals should interpolate seamlessly with proper significance.")
})
test_that( "Triple Mustache Decimal Interpolation", {
#"Decimals should interpolate seamlessly with proper significance."
template <- "\"{{{power}}} jiggawatts!\""
data <- list(power = 1.21)
str <- whisker.render(template, data=data)
expect_equal(str, "\"1.21 jiggawatts!\"", label=deparse(str), info="Decimals should interpolate seamlessly with proper significance.")
})
test_that( "Ampersand Decimal Interpolation", {
#"Decimals should interpolate seamlessly with proper significance."
template <- "\"{{&power}} jiggawatts!\""
data <- list(power = 1.21)
str <- whisker.render(template, data=data)
expect_equal(str, "\"1.21 jiggawatts!\"", label=deparse(str), info="Decimals should interpolate seamlessly with proper significance.")
})
test_that( "Basic Context Miss Interpolation", {
#"Failed context lookups should default to empty strings."
template <- "I ({{cannot}}) be seen!"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "I () be seen!", label=deparse(str), info="Failed context lookups should default to empty strings.")
})
test_that( "Triple Mustache Context Miss Interpolation", {
#"Failed context lookups should default to empty strings."
template <- "I ({{{cannot}}}) be seen!"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "I () be seen!", label=deparse(str), info="Failed context lookups should default to empty strings.")
})
test_that( "Ampersand Context Miss Interpolation", {
#"Failed context lookups should default to empty strings."
template <- "I ({{&cannot}}) be seen!"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "I () be seen!", label=deparse(str), info="Failed context lookups should default to empty strings.")
})
test_that( "Dotted Names - Basic Interpolation", {
#"Dotted names should be considered a form of shorthand for sections."
template <- "\"{{person.name}}\" == \"{{#person}}{{name}}{{/person}}\""
data <- list(person = list(name = "Joe"))
str <- whisker.render(template, data=data)
expect_equal(str, "\"Joe\" == \"Joe\"", label=deparse(str), info="Dotted names should be considered a form of shorthand for sections.")
})
test_that( "Dotted Names - Triple Mustache Interpolation", {
#"Dotted names should be considered a form of shorthand for sections."
template <- "\"{{{person.name}}}\" == \"{{#person}}{{{name}}}{{/person}}\""
data <- list(person = list(name = "Joe"))
str <- whisker.render(template, data=data)
expect_equal(str, "\"Joe\" == \"Joe\"", label=deparse(str), info="Dotted names should be considered a form of shorthand for sections.")
})
test_that( "Dotted Names - Ampersand Interpolation", {
#"Dotted names should be considered a form of shorthand for sections."
template <- "\"{{&person.name}}\" == \"{{#person}}{{&name}}{{/person}}\""
data <- list(person = list(name = "Joe"))
str <- whisker.render(template, data=data)
expect_equal(str, "\"Joe\" == \"Joe\"", label=deparse(str), info="Dotted names should be considered a form of shorthand for sections.")
})
test_that( "Dotted Names - Arbitrary Depth", {
#"Dotted names should be functional to any level of nesting."
template <- "\"{{a.b.c.d.e.name}}\" == \"Phil\""
data <- list(a = list(b = list(c = list(d = list(e = list(name = "Phil"))))))
str <- whisker.render(template, data=data)
expect_equal(str, "\"Phil\" == \"Phil\"", label=deparse(str), info="Dotted names should be functional to any level of nesting.")
})
test_that( "Dotted Names - Broken Chains", {
#"Any falsey value prior to the last part of the name should yield ''."
template <- "\"{{a.b.c}}\" == \"\""
data <- list(a = list())
str <- whisker.render(template, data=data)
expect_equal(str, "\"\" == \"\"", label=deparse(str), info="Any falsey value prior to the last part of the name should yield ''.")
})
test_that( "Dotted Names - Broken Chain Resolution", {
#"Each part of a dotted name should resolve only against its parent."
template <- "\"{{a.b.c.name}}\" == \"\""
data <- list(a = list(b = list()), c = list(name = "Jim"))
str <- whisker.render(template, data=data)
expect_equal(str, "\"\" == \"\"", label=deparse(str), info="Each part of a dotted name should resolve only against its parent.")
})
test_that( "Dotted Names - Initial Resolution", {
#"The first part of a dotted name should resolve as any other name."
template <- "\"{{#a}}{{b.c.d.e.name}}{{/a}}\" == \"Phil\""
data <- list(a = list(b = list(c = list(d = list(e = list(name = "Phil"))))),
b = list(c = list(d = list(e = list(name = "Wrong")))))
str <- whisker.render(template, data=data)
expect_equal(str, "\"Phil\" == \"Phil\"", label=deparse(str), info="The first part of a dotted name should resolve as any other name.")
})
test_that( "Interpolation - Surrounding Whitespace", {
#"Interpolation should not alter surrounding whitespace."
template <- "| {{string}} |"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, "| --- |", label=deparse(str), info="Interpolation should not alter surrounding whitespace.")
})
test_that( "Triple Mustache - Surrounding Whitespace", {
#"Interpolation should not alter surrounding whitespace."
template <- "| {{{string}}} |"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, "| --- |", label=deparse(str), info="Interpolation should not alter surrounding whitespace.")
})
test_that( "Ampersand - Surrounding Whitespace", {
#"Interpolation should not alter surrounding whitespace."
template <- "| {{&string}} |"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, "| --- |", label=deparse(str), info="Interpolation should not alter surrounding whitespace.")
})
test_that( "Interpolation - Standalone", {
#"Standalone interpolation should not alter surrounding whitespace."
template <- " {{string}}\n"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, " ---\n", label=deparse(str), info="Standalone interpolation should not alter surrounding whitespace.")
})
test_that( "Triple Mustache - Standalone", {
#"Standalone interpolation should not alter surrounding whitespace."
template <- " {{{string}}}\n"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, " ---\n", label=deparse(str), info="Standalone interpolation should not alter surrounding whitespace.")
})
test_that( "Ampersand - Standalone", {
#"Standalone interpolation should not alter surrounding whitespace."
template <- " {{&string}}\n"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, " ---\n", label=deparse(str), info="Standalone interpolation should not alter surrounding whitespace.")
})
test_that( "Interpolation With Padding", {
#"Superfluous in-tag whitespace should be ignored."
template <- "|{{ string }}|"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, "|---|", label=deparse(str), info="Superfluous in-tag whitespace should be ignored.")
})
test_that( "Triple Mustache With Padding", {
#"Superfluous in-tag whitespace should be ignored."
template <- "|{{{ string }}}|"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, "|---|", label=deparse(str), info="Superfluous in-tag whitespace should be ignored.")
})
test_that( "Ampersand With Padding", {
#"Superfluous in-tag whitespace should be ignored."
template <- "|{{& string }}|"
data <- list(string = "---")
str <- whisker.render(template, data=data)
expect_equal(str, "|---|", label=deparse(str), info="Superfluous in-tag whitespace should be ignored.")
})
test_that( "Empty Line", {
#"Character vectors starting with the empty string should still render"
template <- c("", "Hello {{place}}!")
data <- list(place = "World")
str <- whisker.render(template, data=data)
expect_equal(str, "\nHello World!", label=deparse(str), info="Templates starting with empty string should still parse.")
})
test_that( "Empty Lines", {
#"Character vectors of multiple empty strings should not collapse to newlines"
template <- c("", "")
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "", label=deparse(str), info="Templates of multiple empty strings should return empty.")
})
whisker/inst/tests/testName.R 0000644 0001751 0000144 00000001421 13527765260 016001 0 ustar hornik users library(testthat)
context("Extra tests")
test_that("names with . work",{
a.test <- 'World'
template <- template <- "Hello {{a.test}}!"
expect_equal( whisker.render(template, list(a.test = a.test), strict=FALSE)
, "Hello World!"
)
})
test_that("referencing with $ works",{
a <- list(test = 'World')
template <- template <- "Hello {{a$test}}!"
expect_equal( whisker.render(template, list(a=a), strict=FALSE)
, "Hello World!"
)
})
context("Github test")
test_that("newlines consistency",{
template <-
"{{#var}}
var is true
{{/var}}
{{^var}}
var is not true
{{/var}}"
expect_equal("var is true\n",whisker.render(template, list(var=TRUE)))
expect_equal("var is not true\n",whisker.render(template, list(var=FALSE)))
})
whisker/inst/tests/testinverted.R 0000644 0001751 0000144 00000022623 13527765260 016750 0 ustar hornik users # Automatically generated from specification file: 'inverted.json'
#
# Inverted Section tags and End Section tags are used in combination to wrap a
# section of the template.
#
# These tags' content MUST be a non-whitespace character sequence NOT
# containing the current closing delimiter; each Inverted Section tag MUST be
# followed by an End Section tag with the same content within the same
# section.
#
# This tag's content names the data to replace the tag. Name resolution is as
# follows:
# 1) Split the name on periods; the first part is the name to resolve, any
# remaining parts should be retained.
# 2) Walk the context stack from top to bottom, finding the first context
# that is a) a hash containing the name as a key OR b) an object responding
# to a method with the given name.
# 3) If the context is a hash, the data is the value associated with the
# name.
# 4) If the context is an object and the method with the given name has an
# arity of 1, the method SHOULD be called with a String containing the
# unprocessed contents of the sections; the data is the value returned.
# 5) Otherwise, the data is the value returned by calling the method with
# the given name.
# 6) If any name parts were retained in step 1, each should be resolved
# against a context stack containing only the result from the former
# resolution. If any part fails resolution, the result should be considered
# falsey, and should interpolate as the empty string.
# If the data is not of a list type, it is coerced into a list as follows: if
# the data is truthy (e.g. `!!data == true`), use a single-element list
# containing the data, otherwise use an empty list.
#
# This section MUST NOT be rendered unless the data list is empty.
#
# Inverted Section and End Section tags SHOULD be treated as standalone when
# appropriate.
#
library(testthat)
context('Spec v1.1, inverted')
test_that( "Falsey", {
#"Falsey sections should have their contents rendered."
template <- "\"{{^boolean}}This should be rendered.{{/boolean}}\""
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "\"This should be rendered.\"", label=deparse(str), info="Falsey sections should have their contents rendered.")
})
test_that( "Truthy", {
#"Truthy sections should have their contents omitted."
template <- "\"{{^boolean}}This should not be rendered.{{/boolean}}\""
data <- list(boolean = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "\"\"", label=deparse(str), info="Truthy sections should have their contents omitted.")
})
test_that( "Context", {
#"Objects and hashes should behave like truthy values."
template <- "\"{{^context}}Hi {{name}}.{{/context}}\""
data <- list(context = list(name = "Joe"))
str <- whisker.render(template, data=data)
expect_equal(str, "\"\"", label=deparse(str), info="Objects and hashes should behave like truthy values.")
})
test_that( "List", {
#"Lists should behave like truthy values."
template <- "\"{{^list}}{{n}}{{/list}}\""
data <- list(list = list(list(n = 1), list(n = 2), list(n = 3)))
str <- whisker.render(template, data=data)
expect_equal(str, "\"\"", label=deparse(str), info="Lists should behave like truthy values.")
})
test_that( "Empty List", {
#"Empty lists should behave like falsey values."
template <- "\"{{^list}}Yay lists!{{/list}}\""
data <- list(list = list())
str <- whisker.render(template, data=data)
expect_equal(str, "\"Yay lists!\"", label=deparse(str), info="Empty lists should behave like falsey values.")
})
test_that( "Doubled", {
#"Multiple inverted sections per template should be permitted."
template <- "{{^bool}}\n* first\n{{/bool}}\n* {{two}}\n{{^bool}}\n* third\n{{/bool}}\n"
data <- list(two = "second", bool = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "* first\n* second\n* third\n", label=deparse(str), info="Multiple inverted sections per template should be permitted.")
})
test_that( "Nested (Falsey)", {
#"Nested falsey sections should have their contents rendered."
template <- "| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |"
data <- list(bool = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "| A B C D E |", label=deparse(str), info="Nested falsey sections should have their contents rendered.")
})
test_that( "Nested (Truthy)", {
#"Nested truthy sections should be omitted."
template <- "| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |"
data <- list(bool = TRUE)
str <- whisker.render(template, data=data)
expect_equal(str, "| A E |", label=deparse(str), info="Nested truthy sections should be omitted.")
})
test_that( "Context Misses", {
#"Failed context lookups should be considered falsey."
template <- "[{{^missing}}Cannot find key 'missing'!{{/missing}}]"
data <- list()
str <- whisker.render(template, data=data)
expect_equal(str, "[Cannot find key 'missing'!]", label=deparse(str), info="Failed context lookups should be considered falsey.")
})
test_that( "Dotted Names - Truthy", {
#"Dotted names should be valid for Inverted Section tags."
template <- "\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"\""
data <- list(a = list(b = list(c = TRUE)))
str <- whisker.render(template, data=data)
expect_equal(str, "\"\" == \"\"", label=deparse(str), info="Dotted names should be valid for Inverted Section tags.")
})
test_that( "Dotted Names - Falsey", {
#"Dotted names should be valid for Inverted Section tags."
template <- "\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\""
data <- list(a = list(b = list(c = FALSE)))
str <- whisker.render(template, data=data)
expect_equal(str, "\"Not Here\" == \"Not Here\"", label=deparse(str), info="Dotted names should be valid for Inverted Section tags.")
})
test_that( "Dotted Names - Broken Chains", {
#"Dotted names that cannot be resolved should be considered falsey."
template <- "\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\""
data <- list(a = list())
str <- whisker.render(template, data=data)
expect_equal(str, "\"Not Here\" == \"Not Here\"", label=deparse(str), info="Dotted names that cannot be resolved should be considered falsey.")
})
test_that( "Surrounding Whitespace", {
#"Inverted sections should not alter surrounding whitespace."
template <- " | {{^boolean}}\t|\t{{/boolean}} | \n"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, " | \t|\t | \n", label=deparse(str), info="Inverted sections should not alter surrounding whitespace.")
})
test_that( "Internal Whitespace", {
#"Inverted should not alter internal whitespace."
template <- " | {{^boolean}} {{! Important Whitespace }}\n {{/boolean}} | \n"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, " | \n | \n", label=deparse(str), info="Inverted should not alter internal whitespace.")
})
test_that( "Indented Inline Sections", {
#"Single-line sections should not alter surrounding whitespace."
template <- " {{^boolean}}NO{{/boolean}}\n {{^boolean}}WAY{{/boolean}}\n"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, " NO\n WAY\n", label=deparse(str), info="Single-line sections should not alter surrounding whitespace.")
})
test_that( "Standalone Lines", {
#"Standalone lines should be removed from the template."
template <- "| This Is\n{{^boolean}}\n|\n{{/boolean}}\n| A Line\n"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "| This Is\n|\n| A Line\n", label=deparse(str), info="Standalone lines should be removed from the template.")
})
test_that( "Standalone Indented Lines", {
#"Standalone indented lines should be removed from the template."
template <- "| This Is\n {{^boolean}}\n|\n {{/boolean}}\n| A Line\n"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "| This Is\n|\n| A Line\n", label=deparse(str), info="Standalone indented lines should be removed from the template.")
})
test_that( "Standalone Line Endings", {
#"\"\\r\\n\" should be considered a newline for standalone tags."
template <- "|\r\n{{^boolean}}\r\n{{/boolean}}\r\n|"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "|\r\n|", label=deparse(str), info="\"\\r\\n\" should be considered a newline for standalone tags.")
})
test_that( "Standalone Without Previous Line", {
#"Standalone tags should not require a newline to precede them."
template <- " {{^boolean}}\n^{{/boolean}}\n/"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "^\n/", label=deparse(str), info="Standalone tags should not require a newline to precede them.")
})
test_that( "Standalone Without Newline", {
#"Standalone tags should not require a newline to follow them."
template <- "^{{^boolean}}\n/\n {{/boolean}}"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "^\n/\n", label=deparse(str), info="Standalone tags should not require a newline to follow them.")
})
test_that( "Padding", {
#"Superfluous in-tag whitespace should be ignored."
template <- "|{{^ boolean }}={{/ boolean }}|"
data <- list(boolean = FALSE)
str <- whisker.render(template, data=data)
expect_equal(str, "|=|", label=deparse(str), info="Superfluous in-tag whitespace should be ignored.")
})
whisker/inst/tests/testpartials.R 0000644 0001751 0000144 00000011176 13527765260 016750 0 ustar hornik users # Automatically generated from specification file: 'partials.json'
#
# Partial tags are used to expand an external template into the current
# template.
#
# The tag's content MUST be a non-whitespace character sequence NOT containing
# the current closing delimiter.
#
# This tag's content names the partial to inject. Set Delimiter tags MUST NOT
# affect the parsing of a partial. The partial MUST be rendered against the
# context stack local to the tag.
#
# Partial tags SHOULD be treated as standalone when appropriate. If this tag
# is used standalone, any whitespace preceding the tag should treated as
# indentation, and prepended to each line of the partial before rendering.
#
library(testthat)
context('Spec v1.1, partials')
test_that( "Basic Behavior", {
#"The greater-than operator should expand to the named partial."
template <- "\"{{>text}}\""
data <- list()
partials <- list(text = "from partial")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "\"from partial\"", label=deparse(str), info="The greater-than operator should expand to the named partial.")
})
test_that( "Context", {
#"The greater-than operator should operate within the current context."
template <- "\"{{>partial}}\""
data <- list(text = "content")
partials <- list(partial = "*{{text}}*")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "\"*content*\"", label=deparse(str), info="The greater-than operator should operate within the current context.")
})
test_that( "Recursion", {
#"The greater-than operator should properly recurse."
template <- "{{>node}}"
data <- list(content = "X", nodes = list(list(content = "Y", nodes = list())))
partials <- list(node = "{{content}}<{{#nodes}}{{>node}}{{/nodes}}>")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "X>", label=deparse(str), info="The greater-than operator should properly recurse.")
})
test_that( "Surrounding Whitespace", {
#"The greater-than operator should not alter surrounding whitespace."
template <- "| {{>partial}} |"
data <- list()
partials <- list(partial = "\t|\t")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "| \t|\t |", label=deparse(str), info="The greater-than operator should not alter surrounding whitespace.")
})
test_that( "Inline Indentation", {
#"Whitespace should be left untouched."
template <- " {{data}} {{> partial}}\n"
data <- list(data = "|")
partials <- list(partial = ">\n>")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, " | >\n>\n", label=deparse(str), info="Whitespace should be left untouched.")
})
test_that( "Standalone Line Endings", {
#"\"\\r\\n\" should be considered a newline for standalone tags."
template <- "|\r\n{{>partial}}\r\n|"
data <- list()
partials <- list(partial = ">")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "|\r\n>|", label=deparse(str), info="\"\\r\\n\" should be considered a newline for standalone tags.")
})
test_that( "Standalone Without Previous Line", {
#"Standalone tags should not require a newline to precede them."
template <- " {{>partial}}\n>"
data <- list()
partials <- list(partial = ">\n>")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, " >\n >>", label=deparse(str), info="Standalone tags should not require a newline to precede them.")
})
test_that( "Standalone Without Newline", {
#"Standalone tags should not require a newline to follow them."
template <- ">\n {{>partial}}"
data <- list()
partials <- list(partial = ">\n>")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, ">\n >\n >", label=deparse(str), info="Standalone tags should not require a newline to follow them.")
})
test_that( "Standalone Indentation", {
#"Each line of the partial should be indented before rendering."
template <- "\\\n {{>partial}}\n/\n"
data <- list(content = "<\n->")
partials <- list(partial = "|\n{{{content}}}\n|\n")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "\\\n |\n <\n->\n |\n/\n", label=deparse(str), info="Each line of the partial should be indented before rendering.")
})
test_that( "Padding Whitespace", {
#"Superfluous in-tag whitespace should be ignored."
template <- "|{{> partial }}|"
data <- list(boolean = TRUE)
partials <- list(partial = "[]")
str <- whisker.render(template, partials=partials, data=data)
expect_equal(str, "|[]|", label=deparse(str), info="Superfluous in-tag whitespace should be ignored.")
})