Title: | Functions for Web Development |
---|---|
Description: | Organizational framework for web development in R including functions to serve static and dynamic content via HTTP methods, includes the html5 package to create HTML pages, and offers other utility functions for common tasks related to web development. |
Authors: | Timothy Conwell |
Maintainer: | Timothy Conwell <[email protected]> |
License: | GPL (>= 3) |
Version: | 1.0.5 |
Built: | 2025-02-08 04:22:31 UTC |
Source: | https://github.com/tconwell/webdeveloper |
Creates HTML option tags for each position of a list of values and labels by calling HTML5::option(), returning a string of HTML to pass to a select tag through HTML5::select().
create_options(x, selected = c(), add_blank = FALSE)
create_options(x, selected = c(), add_blank = FALSE)
x |
A vector which will become the value/label for each option. If named, names become values. |
selected |
A value in the vector passed to mark as the initially selected option in the select tag. |
add_blank |
Boolean, If TRUE, adds a blank option to the top of x. |
A string, with an option tag each row of x.
create_options( x = c("New York", "Los Angeles", "Chicago"), selected = "Chicago" )
create_options( x = c("New York", "Los Angeles", "Chicago"), selected = "Chicago" )
Replace placeholder variables in a HTML document string.
dynamicTemplate(x, replacements = c())
dynamicTemplate(x, replacements = c())
x |
HTML string with placeholder variables that need to be replaced. |
replacements |
A named vector or named list. Names should match a template variable acting as a placeholder in a HTML document string and values should be the text to replace the placeholders with. |
A string of HTML with placeholder values replaced.
dynamicTemplate( x = html(body(templateVar("body_var"))), replacements = c("%%rvar-body_var%%" = div(p("body replacement"))) )
dynamicTemplate( x = html(body(templateVar("body_var"))), replacements = c("%%rvar-body_var%%" = div(p("body replacement"))) )
Replace placeholder variables in a HTML document string, after reading the file into R.
dynamicTemplate2(file, replacements = c())
dynamicTemplate2(file, replacements = c())
file |
Filepath of the HTML file with placeholder variables that need to be replaced. |
replacements |
A named vector or named list. Names should match a template variable acting as a placeholder in a HTML document string and values should be the text to replace the placeholders with. |
A string of HTML with placeholder values replaced.
tmp <- tempfile() writeLines(html(body(templateVar("body_var"))), con = tmp) dynamicTemplate2(file = tmp, replacements = c("%%rvar-body_var%%" = div(p("body replacement"))))
tmp <- tempfile() writeLines(html(body(templateVar("body_var"))), con = tmp) dynamicTemplate2(file = tmp, replacements = c("%%rvar-body_var%%" = div(p("body replacement"))))
Stop HTTP server(s) by calling httpuv::stopServer() or httpuv::stopAllServers().
endServer(x = NULL, all = FALSE)
endServer(x = NULL, all = FALSE)
x |
A server object that was previously returned from serveHTTP. |
all |
TRUE/FALSE, if TRUE, calls httpuv::stopAllServers. |
Nothing.
endServer(all = TRUE)
endServer(all = TRUE)
Find the names of any placeholder variables that exist in a HTML document string.
findTemplateVars(x)
findTemplateVars(x)
x |
HTML string to check for placeholder. |
A vector of the names of template vars found in the HTML string.
findTemplateVars(x = html(body(templateVar("body_var"))))
findTemplateVars(x = html(body(templateVar("body_var"))))
Add a prefix and suffix to an id
idAddAffixes(prefix, id, suffix, prefix_sep = "X", suffix_sep = "-")
idAddAffixes(prefix, id, suffix, prefix_sep = "X", suffix_sep = "-")
prefix |
A string, the prefix to add. |
id |
A string to add a prefix and suffix to. |
suffix |
A string, the suffix to add. |
prefix_sep |
A string, the prefix separator to use. This should be different than suffix_sep. |
suffix_sep |
A string, the suffix separator to use. This should be different than prefix_sep. |
A string.
idAddAffixes("group1", "example", 1)
idAddAffixes("group1", "example", 1)
Add a prefix to an id
idAddPrefix(prefix, id, sep = "X")
idAddPrefix(prefix, id, sep = "X")
prefix |
A string, the prefix to add. |
id |
A string to add a prefix to. |
sep |
A string, the separator to use. |
A string.
idAddSuffix("example", 1)
idAddSuffix("example", 1)
Add a suffix to an id
idAddSuffix(id, suffix, sep = "-")
idAddSuffix(id, suffix, sep = "-")
id |
A string to add a suffix to. |
suffix |
A string, the suffix to add. |
sep |
A string, the separator to use. |
A string.
idAddSuffix("example", 1)
idAddSuffix("example", 1)
Remove a prefix and suffix from an id
idParseAffixes(id, split = "X|-")
idParseAffixes(id, split = "X|-")
id |
A string to remove a prefix and suffix from. |
split |
A regular expression to use for splitting the prefix and suffix from the id. |
A named vector, with prefix, id, and suffix returned in that order.
idParseAffixes(idAddAffixes("group1", "example", 1))
idParseAffixes(idAddAffixes("group1", "example", 1))
Remove a prefix from an id
idParsePrefix(id, split = "X", position = 2)
idParsePrefix(id, split = "X", position = 2)
id |
A string to remove a prefix from. |
split |
A string, the separator to use for splitting the id. |
position |
A integer vector, the position of the split string to return. |
A vector.
idParsePrefix(idAddPrefix("example", 1))
idParsePrefix(idAddPrefix("example", 1))
Remove a suffix from an id
idParseSuffix(id, split = "-", position = 1)
idParseSuffix(id, split = "-", position = 1)
id |
A string to remove a suffix from. |
split |
A string, the separator to use for splitting the id. |
position |
A integer vector, the position of the split string to return. |
A vector.
idParseSuffix(idAddSuffix("example", 1))
idParseSuffix(idAddSuffix("example", 1))
Parse the content type header string to return the content type and boundary
parseContentTypeHeader(x)
parseContentTypeHeader(x)
x |
A string containing the content type header. |
A named list with "content_type" and "boundary" if boundary is present.
parseContentTypeHeader("application/x-www-form-urlencoded")
parseContentTypeHeader("application/x-www-form-urlencoded")
Parse a HTTP request
parseHTTP(x, content_type_header = NULL, consolidate = TRUE)
parseHTTP(x, content_type_header = NULL, consolidate = TRUE)
x |
The body of the HTTP request |
content_type_header |
A string containing the content type header. |
consolidate |
TRUE/FALSE, if TRUE, consolidates items with the same name. |
A named list.
parseHTTP("?form_id=example&col_name=Test+String", "application/x-www-form-urlencoded")
parseHTTP("?form_id=example&col_name=Test+String", "application/x-www-form-urlencoded")
Parse multi-part form data
parseMultiPartFormData(x, boundary)
parseMultiPartFormData(x, boundary)
x |
A vector. |
boundary |
A string, the boundary used for the multi-part form data |
A named list.
parseMultiPartFormData( x = c( "------WebKitFormBoundaryfBloeH49iOmYtO5A", "Content-Disposition: form-data; name=\"form_name\"", "", "Example", "------WebKitFormBoundaryfBloeH49iOmYtO5A", "Content-Disposition: form-data; name=\"form_id\"", "", "test", "------WebKitFormBoundaryfBloeH49iOmYtO5A", "Content-Disposition: form-data; name=\"desktop_file\"; filename=\"limit_type.csv\"", "Content-Type: text/csv", "", "limit_type", "Aggregate", "Occurrence", "------WebKitFormBoundaryfBloeH49iOmYtO5A--" ), boundary = parseContentTypeHeader( "multipart/form-data; boundary=----WebKitFormBoundaryfBloeH49iOmYtO5A")[['boundary']] )
parseMultiPartFormData( x = c( "------WebKitFormBoundaryfBloeH49iOmYtO5A", "Content-Disposition: form-data; name=\"form_name\"", "", "Example", "------WebKitFormBoundaryfBloeH49iOmYtO5A", "Content-Disposition: form-data; name=\"form_id\"", "", "test", "------WebKitFormBoundaryfBloeH49iOmYtO5A", "Content-Disposition: form-data; name=\"desktop_file\"; filename=\"limit_type.csv\"", "Content-Type: text/csv", "", "limit_type", "Aggregate", "Occurrence", "------WebKitFormBoundaryfBloeH49iOmYtO5A--" ), boundary = parseContentTypeHeader( "multipart/form-data; boundary=----WebKitFormBoundaryfBloeH49iOmYtO5A")[['boundary']] )
Helper function for parseMultiPartFormData
parseMultiPartFormParams(x)
parseMultiPartFormParams(x)
x |
A vector, a chunk of multi-part form data to parse. |
A named list.
parseMultiPartFormParams(c("Content-Disposition: form-data; name=\"form_name\"", "", "Example"))
parseMultiPartFormParams(c("Content-Disposition: form-data; name=\"form_name\"", "", "Example"))
Parse a query string
parseQueryString(x, split = "&", consolidate = TRUE)
parseQueryString(x, split = "&", consolidate = TRUE)
x |
A string containing the query string. |
split |
A string, the character to split by. |
consolidate |
TRUE/FALSE, if TRUE, consolidates items with the same name. |
A named list.
parseQueryString("?form_id=example&col_name=Test+String")
parseQueryString("?form_id=example&col_name=Test+String")
Conveniently create HTTP server using httpuv::startServer() or httpuv::runServer().
serveHTTP( host = "127.0.0.1", port = 5001, persistent = FALSE, async = FALSE, static = list(), dynamic = list(), lapply_staticPath = TRUE, static_path_options = list(indexhtml = TRUE, fallthrough = FALSE, html_charset = "utf-8", headers = list(), validation = character(0), exclude = FALSE) )
serveHTTP( host = "127.0.0.1", port = 5001, persistent = FALSE, async = FALSE, static = list(), dynamic = list(), lapply_staticPath = TRUE, static_path_options = list(indexhtml = TRUE, fallthrough = FALSE, html_charset = "utf-8", headers = list(), validation = character(0), exclude = FALSE) )
host |
A string that is a valid IPv4 or IPv6 address that is owned by this server, which the application will listen on. "0.0.0.0" represents all IPv4 addresses and "::/0" represents all IPv6 addresses. Refer to host parameter of httpuv::startServer() for more details. |
port |
The port number to listen on. Refer to port parameter of httpuv::startServer() for more details. |
persistent |
TRUE/FALSE. If FALSE, calls httpuv::startServer(), which returns back to the R session (and would therefore not work with launching a persistent server through a system service as the R session would continue and likely exit/end). If TRUE, calls httpuv::runServer(), which does not return to the R session unless an error or interruption occurs and is suitable for use with system services to start or stop a server. |
async |
TRUE/FALSE, if TRUE, dynamic path requests will be served asynchronously using multicore evaluation, if possible. This is an advanced option and might make it more confusing to debug your app. |
static |
A named list, names should be URL paths, values should be paths to the files to be served statically (such as a HTML file saved somewhere) or staticPath objects if lapply_staticPath is FALSE. |
dynamic |
A named list, names should be URL paths, values should be named alists (use alist instead of list) with alist names equaling a HTTP method (such as "GET" or "POST") and the values being expressions that when evaluated return a named list with valid entries for status, headers, and body as specified by httpuv::startServer(). Refer to httpuv::startServer() for more details on what can be returned as the response. ex. list("/" = alist("GET" = get_function(req), "POST" = post_function(req))) |
lapply_staticPath |
TRUE/FALSE, if TRUE, httpuv::staticPath will be applied to each element of static to create staticPath objects. |
static_path_options |
A named list, passed to httpuv::staticPathOptions. |
serveHTTP is a convenient way to start a HTTP server that works for both static and dynamically created pages. It offers a simplified and organized interface to httpuv::startServer()/httpuv::runServer() that makes serving static and dynamic pages easier. For dynamic pages, the expression evaluated when a browser requests a dynamically served path should likely be an expression/function that has "req" as a parameter. Per the Rook specification implemented by httpuv, "req" is the R environment in which browser request information is collected. Therefore, to access HTTP request headers, inputs, etc. in a function served by a dynamic path, "req" should be a parameter of that function. For the dynamic parameter of serveHTTP, list("/" = alist("GET" = get_homepage(req))) would be a suitable way to call the function get_homepage(req) when the root path of a website is requested with the GET method. The req environment has the following variables: request_method = req$REQUEST_METHOD, script_name = req$SCRIPT_NAME, path_info = req$PATH_INFO, query_string = req$QUERY_STRING, server_name = req$SERVER_NAME, server_port = req$SERVER_PORT, headers = req$HEADERS, rook_input = req[["rook.input"]]$read_lines(), rook_version = req[["rook.version"]]$read_lines(), rook_url_scheme = req[["rook.url_scheme"]]$read_lines(), rook_error_stream = req[["rook.errors"]]$read_lines()
A HTTP web server on the specified host and port.
# Run both functions and go to http://127.0.0.1:5001/ in a web browser get_example <- function(req){ html <- doctype( html( head(), body( h1("Hello"), p("Here is a list of some of the variables included in the req environment that were associated with this request:"), ul( li(paste0("req$REQUEST_METHOD = ", req$REQUEST_METHOD)), li(paste0("req$SCRIPT_NAME = ", req$SCRIPT_NAME)), li(paste0("req$PATH_INFO = ", req$PATH_INFO)), li(paste0("req$QUERY_STRING = ", req$QUERY_STRING)), li(paste0("req$SERVER_NAME = ", req$SERVER_NAME)), li(paste0("req$SERVER_PORT = ", req$SERVER_PORT)) ), p("You can use parseQueryString to deal with inputs passed through query strings as well as passed through the input stream."), p("params <- parseQueryString(req[[\"rook.input\"]]$read_lines()) will give you a named list of parameters. See also parseHTTP.") ) ) ) return( list( status = 200L, headers = list('Content-Type' = 'text/html'), body = html ) ) } serveHTTP( host = "127.0.0.1", port = 5001, persistent = FALSE, static = list(), dynamic = list( "/" = alist( "GET" = get_example(req) ) ) )
# Run both functions and go to http://127.0.0.1:5001/ in a web browser get_example <- function(req){ html <- doctype( html( head(), body( h1("Hello"), p("Here is a list of some of the variables included in the req environment that were associated with this request:"), ul( li(paste0("req$REQUEST_METHOD = ", req$REQUEST_METHOD)), li(paste0("req$SCRIPT_NAME = ", req$SCRIPT_NAME)), li(paste0("req$PATH_INFO = ", req$PATH_INFO)), li(paste0("req$QUERY_STRING = ", req$QUERY_STRING)), li(paste0("req$SERVER_NAME = ", req$SERVER_NAME)), li(paste0("req$SERVER_PORT = ", req$SERVER_PORT)) ), p("You can use parseQueryString to deal with inputs passed through query strings as well as passed through the input stream."), p("params <- parseQueryString(req[[\"rook.input\"]]$read_lines()) will give you a named list of parameters. See also parseHTTP.") ) ) ) return( list( status = 200L, headers = list('Content-Type' = 'text/html'), body = html ) ) } serveHTTP( host = "127.0.0.1", port = 5001, persistent = FALSE, static = list(), dynamic = list( "/" = alist( "GET" = get_example(req) ) ) )
Create a string to use as a placeholder variable in a HTML document.
templateVar(x)
templateVar(x)
x |
Name of placeholder. |
A string.
templateVar("my_dynamic_var")
templateVar("my_dynamic_var")