PageRenderTime 17ms CodeModel.GetById 10ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/R/render.r

http://github.com/hadley/sinartra
R | 45 lines | 23 code | 4 blank | 18 comment | 4 complexity | c1ddcdabf442ce6bea589a2c4bb4de21 MD5 | raw file
 1#' Send output to browser
 2#'
 3#' @param text a character vector 
 4#' @param status http status code
 5#' @param mime_type mime type
 6#' @param headers character vector of http headers
 7render <- function(text, status = 200L, mime_type = "text/html", headers = c()) {
 8  text <- stringr::str_c(text, collapse = "\n")
 9  list(
10    payload = text, 
11    "content-type" = mime_type, 
12    "headers" = headers,
13    "status code" = status)
14}
15
16#' Render template using brew.
17#' Templates are located in \code{views}.
18#' 
19#' @param template string giving template name (file name without extension)
20#' @param params list of parameters to be evaluated in template
21#' @param path web app path
22#' @param parent parent.frame() to be used
23#' @export
24render_brew <- function(template, params = NULL, path = getwd(), parent = parent.frame()) {
25  path <- file.path(path, "views", stringr::str_c(template, ".html"))
26  if (!file.exists(path)) stop("Can not find ", template, " template ",
27    call. = FALSE)
28
29  if (is.list(params) && length(params) > 0) {
30    env <- list2env(params, parent = parent)
31  } else {
32    env <- parent
33  }
34
35  render(capture.output(brew::brew(path, envir = env)))
36}
37
38#' Produce JSON from an R object
39#'
40#' @param object R object to be converted to JSON
41#' @export
42render_json <- function(object) {
43  json <- rjson::toJSON(object)
44  render(json, mime_type = "application/json")
45}