/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
  7. render <- 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. #' Render template using brew.
  16. #' Templates are located in \code{views}.
  17. #'
  18. #' @param template string giving template name (file name without extension)
  19. #' @param params list of parameters to be evaluated in template
  20. #' @param path web app path
  21. #' @param parent parent.frame() to be used
  22. #' @export
  23. render_brew <- function(template, params = NULL, path = getwd(), parent = parent.frame()) {
  24. path <- file.path(path, "views", stringr::str_c(template, ".html"))
  25. if (!file.exists(path)) stop("Can not find ", template, " template ",
  26. call. = FALSE)
  27. if (is.list(params) && length(params) > 0) {
  28. env <- list2env(params, parent = parent)
  29. } else {
  30. env <- parent
  31. }
  32. render(capture.output(brew::brew(path, envir = env)))
  33. }
  34. #' Produce JSON from an R object
  35. #'
  36. #' @param object R object to be converted to JSON
  37. #' @export
  38. render_json <- function(object) {
  39. json <- rjson::toJSON(object)
  40. render(json, mime_type = "application/json")
  41. }