### Run a Shiny Example App Source: https://rstudio.github.io/htmltools/articles/htmltools.html This command runs the '01_hello' example Shiny application. Ensure the shiny package is loaded. ```r library(shiny) runExample("01_hello") ``` -------------------------------- ### Install htmltools package Source: https://rstudio.github.io/htmltools/index.html Install the stable version of the package from CRAN. ```R install.packages("htmltools") ``` -------------------------------- ### Example of tagList usage Source: https://rstudio.github.io/htmltools/reference/tagList.html Demonstrates creating a list containing h1, h2, and p tags. ```R tagList( h1("Title"), h2("Header text", style = "color: red;"), p("Text here") ) #>

Title

#>

Header text

#>

Text here

``` -------------------------------- ### Capture Plot Usage Examples Source: https://rstudio.github.io/htmltools/reference/capturePlot.html Examples demonstrating default usage, custom dimensions, and using alternative graphics devices like SVG. ```R if (FALSE) { # rlang::is_interactive() # Default settings res <- capturePlot(plot(cars)) # View result browseURL(res) # Clean up unlink(res) # Custom width/height pngpath <- tempfile(fileext = ".png") capturePlot(plot(pressure), pngpath, width = 800, height = 375) browseURL(pngpath) unlink(pngpath) # Use a custom graphics device (e.g., SVG) if (capabilities("cairo")) { svgpath <- capturePlot( plot(pressure), tempfile(fileext = ".svg"), grDevices::svg, width = 8, height = 3.75 ) browseURL(svgpath) unlink(svgpath) } } ``` -------------------------------- ### Create and attach HTML dependencies Source: https://rstudio.github.io/htmltools/reference/htmlDependencies.html Examples of defining JavaScript and CSS dependencies and attaching them to tag objects using various methods. ```R # Create a JavaScript dependency dep <- htmlDependency("jqueryui", "1.11.4", c(href="shared/jqueryui"), script = "jquery-ui.min.js") # A CSS dependency htmlDependency( "font-awesome", "4.5.0", c(href="shared/font-awesome"), stylesheet = "css/font-awesome.min.css" ) #> List of 10 #> $ name : chr "font-awesome" #> $ version : chr "4.5.0" #> $ src :List of 1 #> ..$ href: chr "shared/font-awesome" #> $ meta : NULL #> $ script : NULL #> $ stylesheet: chr "css/font-awesome.min.css" #> $ head : NULL #> $ attachment: NULL #> $ package : NULL #> $ all_files : logi TRUE #> - attr(*, "class")= chr "html_dependency" # A few different ways to add the dependency to tag objects: # Inline as a child of the div() div("Code here", dep) #>
Code here
# Inline in a tagList tagList(div("Code here"), dep) #>
Code here
# With attachDependencies attachDependencies(div("Code here"), dep) #>
Code here
``` -------------------------------- ### Install development version of htmltools Source: https://rstudio.github.io/htmltools/index.html Install the latest development version from GitHub using the remotes package. ```R remotes::install_github("rstudio/htmltools") ``` -------------------------------- ### Create CSS Style Declarations with css() Source: https://rstudio.github.io/htmltools/reference/css.html Example demonstrating how to use the css() function to create a CSS style string. It shows conversion of R-friendly property names (like font.family) to CSS syntax and handling of !important declarations. ```R padding <- 6 css( font.family = "Helvetica, sans-serif", margin = paste0(c(10, 20, 10, 20), "px"), "padding!" = if (!is.null(padding)) padding ) #> [1] "font-family:Helvetica, sans-serif;margin:10px 20px 10px 20px;padding:6 !important;" ``` -------------------------------- ### Use tagAddRenderHook for dynamic tag modification Source: https://rstudio.github.io/htmltools/reference/tagAddRenderHook.html Examples demonstrating how to use render hooks to change tag names, add attributes, append children, manage dependencies, or replace the tag entirely. ```R # Have a place holder div and return a span instead obj <- div("example", .renderHook = function(x) { x$name <- "span" x }) obj$name # "div" #> [1] "div" print(obj) # Prints as a `span` #> example # Add a class to the tag # Should print a `span` with class `"extra"` spanExtra <- tagAddRenderHook(obj, function(x) { tagAppendAttributes(x, class = "extra") }) spanExtra #> example # Replace the previous render method # Should print a `div` with class `"extra"` divExtra <- tagAddRenderHook(obj, replace = TRUE, function(x) { tagAppendAttributes(x, class = "extra") }) divExtra #>
example
# Add more child tags spanExtended <- tagAddRenderHook(obj, function(x) { tagAppendChildren(x, " ", tags$strong("bold text")) }) spanExtended #> #> example #> #> bold text #> # Add a new html dependency newDep <- tagAddRenderHook(obj, function(x) { fa <- htmlDependency( "font-awesome", "4.5.0", c(href="shared/font-awesome"), stylesheet = "css/font-awesome.min.css") attachDependencies(x, fa, append = TRUE) }) # Also add a jqueryui html dependency htmlDependencies(newDep) <- htmlDependency( "jqueryui", "1.11.4", c(href="shared/jqueryui"), script = "jquery-ui.min.js") # At render time, both dependencies will be found renderTags(newDep)$dependencies #> [[1]] #> List of 10 #> $ name : chr "jqueryui" #> $ version : chr "1.11.4" #> $ src :List of 1 #> ..$ href: chr "shared/jqueryui" #> $ meta : NULL #> $ script : chr "jquery-ui.min.js" #> $ stylesheet: NULL #> $ head : NULL #> $ attachment: NULL #> $ package : NULL #> $ all_files : logi TRUE #> - attr(*, "class")= chr "html_dependency" #> #> [[2]] #> List of 10 #> $ name : chr "font-awesome" #> $ version : chr "4.5.0" #> $ src :List of 1 #> ..$ href: chr "shared/font-awesome" #> $ meta : NULL #> $ script : NULL #> $ stylesheet: chr "css/font-awesome.min.css" #> $ head : NULL #> $ attachment: NULL #> $ package : NULL #> $ all_files : logi TRUE #> - attr(*, "class")= chr "html_dependency" #> # Ignore the original tag and return something completely new. newObj <- tagAddRenderHook(obj, function(x) { tags$p("Something else") }) newObj #>

Something else

``` -------------------------------- ### HTML Tag Creation Source: https://rstudio.github.io/htmltools/reference/builder.html Demonstrates how to create common and custom HTML tags using the htmltools package in R. Includes examples for basic tags, nested tags, and tags with attributes. ```APIDOC ## Create HTML tags This section describes how to create HTML tags using the `htmltools` R package. Common HTML tags can be created by calling their names directly (e.g., `div()`), while less common tags can be accessed through the `tags` list (e.g., `tags$article()`). For other non-HTML/SVG tags, use the `tag()` constructor. ### Available Tag Constructors - `p(..., .noWS = NULL, .renderHook = NULL)` - `h1(..., .noWS = NULL, .renderHook = NULL)` - `h2(..., .noWS = NULL, .renderHook = NULL)` - `h3(..., .noWS = NULL, .renderHook = NULL)` - `h4(..., .noWS = NULL, .renderHook = NULL)` - `h5(..., .noWS = NULL, .renderHook = NULL)` - `h6(..., .noWS = NULL, .renderHook = NULL)` - `a(..., .noWS = NULL, .renderHook = NULL)` - `br(..., .noWS = NULL, .renderHook = NULL)` - `div(..., .noWS = NULL, .renderHook = NULL)` - `span(..., .noWS = NULL, .renderHook = NULL)` - `pre(..., .noWS = NULL, .renderHook = NULL)` - `code(..., .noWS = NULL, .renderHook = NULL)` - `img(..., .noWS = NULL, .renderHook = NULL)` - `strong(..., .noWS = NULL, .renderHook = NULL)` - `em(..., .noWS = NULL, .renderHook = NULL)` - `hr(..., .noWS = NULL, .renderHook = NULL)` - `tag(_tag_name, varArgs, .noWS = NULL, .renderHook = NULL)` ### Arguments - `...`: Tag attributes (named arguments) and children (unnamed arguments). A named argument with an `NA` value is rendered as a boolean attribute. Children can include other tags, `HTML()` strings, `htmlDependency()`s, single-element atomic vectors, or lists of these. - `.noWS`: Character vector to omit whitespace. Valid options: `before`, `after`, `outside`, `after-begin`, `before-end`. - `.renderHook`: A function or list of functions to call during rendering. It should accept the tag as an argument and return a renderable object. - `_tag_name`: Character string for the tag name when using the `tag()` constructor. - `varArgs`: List of tag attributes and children for the `tag()` constructor. ### Value A `shiny.tag` class object that can be converted to an HTML string. ### Examples ```R # Create a simple HTML structure tags$html( tags$head( tags$title('My first page') ), tags$body( h1('My first heading'), p('My first paragraph, with some ', strong('bold'), ' text.'), div( id = 'myDiv', class = 'simpleDiv', 'Here is a div with some attributes.' ) ) ) # Create an audio tag with a boolean control attribute tags$audio( controls = NA, tags$source( src = "myfile.wav", type = "audio/wav" ) ) # Suppress whitespace between tags tags$span( tags$strong("I'm strong", .noWS="outside") ) ``` ``` -------------------------------- ### Set Custom CSS Properties with css Source: https://rstudio.github.io/htmltools/news/index.html Use names starting with -- to define custom CSS properties or variables. ```R css("--font_size" = "3em") ``` ```R css(font_size = "3em") ``` -------------------------------- ### Include Markdown Content From File Source: https://rstudio.github.io/htmltools/reference/include.html Use includeMarkdown to load and render Markdown content from a file. This function requires the 'markdown' package to be installed. ```R includeMarkdown(path) ``` -------------------------------- ### Example of HTML marking Source: https://rstudio.github.io/htmltools/reference/HTML.html Demonstrates how HTML marking prevents escaping of tags within a div element. ```R el <- div(HTML("I like turtles")) cat(as.character(el)) #>
I like turtles
``` -------------------------------- ### Generate PNG Plot Tag Source: https://rstudio.github.io/htmltools/reference/plotTag.html Example of generating a PNG image tag from a plot. This demonstrates basic usage with a plotting expression and alt text. ```R img <- plotTag({ plot(cars) }, "A plot of the 'cars' dataset", width = 375, height = 275) ``` -------------------------------- ### Generate SVG Plot Tag Source: https://rstudio.github.io/htmltools/reference/plotTag.html Example of generating an SVG image tag from a plot using the `grDevices::svg` device. This shows how to specify a different device, pixel ratio, and MIME type for vector graphics. ```R plotTag( plot(pressure), "A plot of the 'pressure' dataset", device = grDevices::svg, width = 375, height = 275, pixelratio = 1/72, mimeType = "image/svg+xml" ) ``` -------------------------------- ### Generate Conditional Tags/Dependencies with tagFunction() Source: https://rstudio.github.io/htmltools/news/index.html Create tagFunction() for generating tags and/or htmlDependency()s conditionally based on the rendering context. Refer to ?tagFunction for detailed examples. ```R tagFunction(name, ..., render = NULL) ``` -------------------------------- ### Create a tagList Source: https://rstudio.github.io/htmltools/reference/tagList.html Initializes a list of HTML tags. ```R tagList(...) ``` -------------------------------- ### Singleton usage and check Source: https://rstudio.github.io/htmltools/reference/singleton.html Use singleton to wrap content for single inclusion. Use is.singleton to verify if an object is marked as a singleton. ```R singleton(x, value = TRUE) is.singleton(x) ``` -------------------------------- ### Initialize tagQuery Object Source: https://rstudio.github.io/htmltools/articles/tagQuery.html Create a tagQuery object by passing it a tag() or tagList(). By default, all input tags are selected. ```R library(htmltools) tagQuery(div(a())) #> `$allTags()`: #>
#> #>
#> #> `$selectedTags()`: `$allTags()` ``` -------------------------------- ### Apply fill roles to HTML elements Source: https://rstudio.github.io/htmltools/reference/bindFillRole.html Demonstrates how to mark a container and its child item to enable filling behavior. ```R tagz <- div( id = "outer", style = css( height = "600px", border = "3px red solid" ), div( id = "inner", style = css( height = "400px", border = "3px blue solid" ) ) ) # Inner doesn't fill outer if (interactive()) browsable(tagz) tagz <- bindFillRole(tagz, container = TRUE) tagz <- bindFillRole(tagz, item = TRUE, .cssSelector = "#inner") # Inner does fill outer if (interactive()) browsable(tagz) ``` -------------------------------- ### Get HTML Tag Attribute Value Source: https://rstudio.github.io/htmltools/reference/tagAppendAttributes.html Use `tagGetAttribute` to retrieve the value of a specified attribute from an HTML tag. This function returns the attribute's value as a string. ```R tagGetAttribute(div(foo = "bar"), "foo") ``` -------------------------------- ### Include HTML Content From File Source: https://rstudio.github.io/htmltools/reference/include.html Use includeHTML to load HTML content from a specified file path. Relative paths are recommended. ```R includeHTML(path) ``` -------------------------------- ### Generate HTML using tags and withTags Source: https://rstudio.github.io/htmltools/reference/withTags.html Comparison of standard tag usage versus the simplified withTags syntax, including whitespace configuration. ```R # Using tags$ each time tags$div(class = "myclass", tags$h3("header"), tags$p("text") ) #>
#>

header

#>

text

#>
# Equivalent to above, but using withTags withTags( div(class = "myclass", h3("header"), p("text") ) ) #>
#>

header

#>

text

#>
# Setting .noWS for all tags in withTags() withTags( div( class = "myclass", h3("header"), p("One", strong(span("two")), "three") ), .noWS = c("outside", "inside") ) #>

header

Onetwothree

``` -------------------------------- ### Implement print method for HTML Source: https://rstudio.github.io/htmltools/reference/html_print.html Provides an implementation of the base::print() method for HTML content. Use this for printing HTML objects. ```R html_print( html, background = "white", viewer = getOption("viewer", utils::browseURL) ) ``` -------------------------------- ### Append, Check, and Get Tag Attributes Source: https://rstudio.github.io/htmltools/reference/tagAppendAttributes.html Functions to manage HTML tag attributes: append new attributes, check for existing attributes, and retrieve attribute values. Supports CSS selectors for targeting specific tags. ```APIDOC ## tagAppendAttributes, tagHasAttribute, tagGetAttribute ### Description Append (`tagAppendAttributes()`), check existence (`tagHasAttribute()`), and obtain the value (`tagGetAttribute()`) of HTML attribute(s). ### tagAppendAttributes #### Description Appends attributes to an HTML tag. If a CSS selector is provided, attributes are appended to matching inner tags. #### Method `tagAppendAttributes(tag, ..., .cssSelector = NULL)` #### Arguments - **tag** (tag object) - The HTML tag to modify. - **...** (named argument-value pairs) - Attributes to append. A `NA` value renders as a boolean attribute. - **.cssSelector** (character string, optional) - A CSS selector for targeting inner tags. Supports type, class, id, and universal selectors. If used, tag children are flattened. ### tagHasAttribute #### Description Checks if an HTML tag has a specific attribute. #### Method `tagHasAttribute(tag, attr)` #### Arguments - **tag** (tag object) - The HTML tag to check. - **attr** (character string) - The name of the attribute to check for. ### tagGetAttribute #### Description Retrieves the value of a specific attribute from an HTML tag. #### Method `tagGetAttribute(tag, attr)` #### Arguments - **tag** (tag object) - The HTML tag to query. - **attr** (character string) - The name of the attribute whose value to retrieve. ### Request Example (tagAppendAttributes) ```R html <- div(a()) tagAppendAttributes(html, class = "foo") ``` ### Response Example (tagAppendAttributes) ```html
``` ### Request Example (tagAppendAttributes with .cssSelector) ```R html <- div(a()) tagAppendAttributes(html, .cssSelector = "a", class = "bar") ``` ### Response Example (tagAppendAttributes with .cssSelector) ```html
``` ### Request Example (tagAppendAttributes with boolean attribute) ```R html <- div(a()) tagAppendAttributes(html, contenteditable = NA) ``` ### Response Example (tagAppendAttributes with boolean attribute) ```html
``` ### Request Example (tagHasAttribute) ```R tagHasAttribute(div(foo = "bar"), "foo") ``` ### Response Example (tagHasAttribute) ```R [1] TRUE ``` ### Request Example (tagGetAttribute) ```R tagGetAttribute(div(foo = "bar"), "foo") ``` ### Response Example (tagGetAttribute) ```R [1] "bar" ``` ### See also `tagAppendChildren()`, `tagQuery()` ``` -------------------------------- ### defaultPngDevice() Source: https://rstudio.github.io/htmltools/reference/defaultPngDevice.html Returns the best PNG-based graphics device function for the current system. ```APIDOC ## GET defaultPngDevice ### Description Returns the best PNG-based graphics device for your system, in the opinion of the htmltools maintainers. On Mac, grDevices::png() is used; on all other platforms, either ragg::agg_png() or Cairo::CairoPNG() are used if their packages are installed. Otherwise, grDevices::png() is used. ### Method GET ### Endpoint defaultPngDevice() ### Response #### Success Response (200) - **device** (function) - A graphics device function. ``` -------------------------------- ### singleton function Source: https://rstudio.github.io/htmltools/reference/singleton.html Wraps content to ensure it is included only once in the generated document. ```APIDOC ## singleton(x, value = TRUE) ### Description Use singleton to wrap contents (tag, text, HTML, or lists) that should be included in the generated document only once, yet may appear in the document-generating code more than once. Only the first appearance of the content (in document order) will be used. ### Arguments - **x** (tag, text, HTML, or list) - Required - The content to be wrapped. - **value** (boolean) - Optional - Whether the object should be a singleton. Defaults to TRUE. ``` -------------------------------- ### HTML tag constructor signatures Source: https://rstudio.github.io/htmltools/reference/builder.html Lists the function signatures for common HTML tag builders and the generic tag constructor. ```R tags p(..., .noWS = NULL, .renderHook = NULL) h1(..., .noWS = NULL, .renderHook = NULL) h2(..., .noWS = NULL, .renderHook = NULL) h3(..., .noWS = NULL, .renderHook = NULL) h4(..., .noWS = NULL, .renderHook = NULL) h5(..., .noWS = NULL, .renderHook = NULL) h6(..., .noWS = NULL, .renderHook = NULL) a(..., .noWS = NULL, .renderHook = NULL) br(..., .noWS = NULL, .renderHook = NULL) div(..., .noWS = NULL, .renderHook = NULL) span(..., .noWS = NULL, .renderHook = NULL) pre(..., .noWS = NULL, .renderHook = NULL) code(..., .noWS = NULL, .renderHook = NULL) img(..., .noWS = NULL, .renderHook = NULL) strong(..., .noWS = NULL, .renderHook = NULL) em(..., .noWS = NULL, .renderHook = NULL) hr(..., .noWS = NULL, .renderHook = NULL) tag(`_tag_name`, varArgs, .noWS = NULL, .renderHook = NULL) ``` -------------------------------- ### Load shiny library Source: https://rstudio.github.io/htmltools/articles/htmltools.html Load the shiny library to integrate tags into a UI object. ```R library(shiny) ``` -------------------------------- ### Initialize tagQuery Source: https://rstudio.github.io/htmltools/reference/tagQuery.html Initializes a tagQuery object with a tag, tagList, or list of tags for subsequent manipulation. ```R tagQuery(tags) ``` -------------------------------- ### Prepend and Append Children to Selected Tags Source: https://rstudio.github.io/htmltools/articles/tagQuery.html Use `$prepend()` to insert new tags before the children of selected elements, and `$append()` to insert them after. These methods modify the selected tags and return the tagQuery object. ```R (html <- div(p(a()))) #>
#>

#> #>

#>
``` ```R tagQ <- tagQuery(html) # Equivalent to html %>% tagInsertChildren(.cssSelector = "p", after = 0, span()) %>% tagAppendChildren(.cssSelector = "p", tags$table()) tagQ$ find("p")$ prepend(span())$ append(tags$table())$ allTags() #>
#>

#> #> #>
#>

#>
``` -------------------------------- ### Include CSS Content From File Source: https://rstudio.github.io/htmltools/reference/include.html Use includeCSS to load CSS content from a file and apply it. Additional attributes can be passed via '...'. ```R includeCSS(path, ...) ``` -------------------------------- ### Create HTML for Dependencies Source: https://rstudio.github.io/htmltools/reference/renderDependencies.html Generates HTML markup for including dependencies in an HTML document. Use this function when you need to programmatically create HTML tags for CSS, JavaScript, or other assets. ```R renderDependencies( dependencies, srcType = c("href", "file"), encodeFunc = urlEncodePath, hrefFilter = identity ) ``` -------------------------------- ### Arrange htmlwidgets with htmltools Source: https://rstudio.github.io/htmltools/index.html Combine multiple htmlwidgets into a single browsable HTML structure. ```R library(htmltools) library(plotly) browsable(tagList( plot_ly(diamonds, x = ~carat, height = 200), plot_ly(diamonds, x = ~price, height = 200) )) ``` -------------------------------- ### Handle Dependencies Without Files in copyDependencyToDir() Source: https://rstudio.github.io/htmltools/news/index.html copyDependencyToDir() no longer creates empty directories for dependencies lacking files. This streamlines directory creation and avoids unnecessary empty folders. ```R copyDependencyToDir(dependency, path, ...) ``` -------------------------------- ### Include JavaScript Content From File Source: https://rstudio.github.io/htmltools/reference/include.html Use includeScript to load JavaScript content from a file. Additional attributes can be passed via '...'. ```R includeScript(path, ...) ``` -------------------------------- ### tagQuery Constructor Source: https://rstudio.github.io/htmltools/reference/tagQuery.html Initializes a tagQuery object from a tag, tagList, or list of tags. ```APIDOC ## tagQuery(tags) ### Description Initializes a queryable interface for HTML tag objects. Note that the input structure is altered for performance reasons, though the rendered HTML remains identical. ### Parameters #### Request Body - **tags** (tag|tagList|list) - Required - The HTML tag structure to be queried or modified. ### Response - **object** (tagQuery) - A class instance providing methods for querying and modifying the provided tags. ``` -------------------------------- ### Simplify tag syntax with withTags Source: https://rstudio.github.io/htmltools/articles/htmltools.html Use withTags to avoid prefixing every tag function with tags$. ```R withTags({ div(class="header", checked=NA, p("Ready to take the Shiny tutorial? If so"), a(href="shiny.posit.co/tutorial", "Click Here!") ) }) ``` -------------------------------- ### Benchmark tagQuery vs. tagAppend Source: https://rstudio.github.io/htmltools/articles/tagQuery.html Compares the execution time of modifying HTML using `tagQuery()` for multiple operations versus using `tagInsertChildren()` and `tagAppendChildren()` sequentially. `tagQuery()` is expected to be faster. ```r library(magrittr) html <- div(p(a())) bench::mark( tagQuery = tagQuery(html)$ find("p")$ prepend(span())$ append(tags$table())$ allTags(), tagAppend = html %>% tagInsertChildren(.cssSelector = "p", after = 0, span()) %>% tagAppendChildren(.cssSelector = "p", tags$table()), check = FALSE, time_unit = "us" ) #> # A tibble: 2 × 6 #> expression min median `itr/sec` mem_alloc `gc/sec` #> #> 1 tagQuery 697. 752. 1322. 11.4KB 14.8 #> 2 tagAppend 1313. 1379. 718. 50.5KB 15.5 ``` -------------------------------- ### Query Methods Source: https://rstudio.github.io/htmltools/reference/tagQuery.html Methods for navigating and selecting subsets of the tag structure using CSS selectors or R functions. ```APIDOC ## Query Methods ### Methods - **$find(cssSelector)**: Get descendants filtered by CSS selector. - **$children(cssSelector = NULL)**: Get direct children, optionally filtered. - **$siblings(cssSelector = NULL)**: Get siblings, optionally filtered. - **$parent(cssSelector = NULL)**: Get parent, optionally filtered. - **$parents(cssSelector = NULL)**: Get ancestors, optionally filtered. - **$closest(cssSelector = NULL)**: Get closest ancestor (including self) satisfying selector. - **$filter(fn)**: Filter selection using an R function or CSS selector. - **$length()**: Returns the number of currently selected tags. ``` -------------------------------- ### Include Text Content From File Source: https://rstudio.github.io/htmltools/reference/include.html Use includeText to load plain text content from a file. Note that includeText escapes its contents and renders hard breaks and multiple spaces as a single space. For preformatted text, consider using pre() or includeMarkdown. ```R includeText(path) ``` -------------------------------- ### Manage HTML object browsability Source: https://rstudio.github.io/htmltools/reference/browsable.html Use browsable to set the render behavior of an object and is.browsable to verify its current state. ```R browsable(x, value = TRUE) is.browsable(x) ``` -------------------------------- ### Determine the best PNG device Source: https://rstudio.github.io/htmltools/reference/defaultPngDevice.html Returns a graphics device function suitable for the current system. It prioritizes ragg or Cairo if available on non-Mac platforms. ```R defaultPngDevice() ``` -------------------------------- ### Create HTML5 tags with boolean attributes Source: https://rstudio.github.io/htmltools/reference/builder.html Demonstrates using NA as an attribute value to render boolean HTML attributes. ```R tags$audio( controls = NA, tags$source( src = "myfile.wav", type = "audio/wav" ) ) ``` -------------------------------- ### Include Content From Files Source: https://rstudio.github.io/htmltools/reference/include.html Functions to load HTML, text, Markdown, CSS, or JavaScript from files and convert them into HTML tags. ```APIDOC ## includeHTML, includeText, includeMarkdown, includeCSS, includeScript ### Description These functions provide a convenient way to include an extensive amount of HTML, textual, Markdown, CSS, or JavaScript content, rather than using a large literal R string. ### Method N/A (These are R functions, not API endpoints) ### Endpoint N/A ### Parameters #### Arguments - **path** (string) - Required - The path of the file to be included. It is highly recommended to use a relative path (the base path being the Shiny application directory), not an absolute path. - **...** - Any additional attributes to be applied to the generated tag. ### Request Example ```R # Example for includeHTML includeHTML("path/to/your/file.html") # Example for includeText includeText("path/to/your/file.txt") # Example for includeMarkdown includeMarkdown("path/to/your/file.md") # Example for includeCSS includeCSS("path/to/your/style.css") # Example for includeScript includeScript("path/to/your/script.js") ``` ### Response #### Success Response (Tag Object) - Returns an HTML tag object representing the included content. #### Response Example ```R # Example of a returned tag object (conceptual) # # #
...content from file...
``` ### Details - `includeText` escapes its contents, but does no other processing. Hard breaks and multiple spaces will be rendered as a single space character. Wrap with `pre()` for preformatted text or use `includeMarkdown`. - `includeMarkdown` requires the `markdown` package. ``` -------------------------------- ### Copy HTML Dependency to Directory Source: https://rstudio.github.io/htmltools/reference/copyDependencyToDir.html Copies an HTML dependency to a subdirectory within the specified output directory. The subdirectory name is formed by combining the dependency's name and version. Optionally, the version number can be omitted from the subdirectory name by setting `options(htmltools.dir.version = FALSE)`. ```R copyDependencyToDir(dependency, outputDir, mustWork = TRUE) ``` -------------------------------- ### Create HTML tags Source: https://rstudio.github.io/htmltools/reference/index.html Functions for generating standard HTML elements and tag lists. ```APIDOC ## Create HTML tags ### Description Functions to create HTML tags such as p(), h1(), div(), and span(), or aggregate them using tagList(). ### Methods tags, p, h1, h2, h3, h4, h5, h6, a, br, div, span, pre, code, img, strong, em, hr, tag, tagList ``` -------------------------------- ### Insert Siblings Before and After Selected Tags Source: https://rstudio.github.io/htmltools/articles/tagQuery.html Use `$before()` to insert new tags before the selected tags, and `$after()` to insert them after. These operations modify the HTML structure and return the tagQuery object. ```R (html <- div(p(a()))) #>
#>

#> #>

#>
``` ```R tagQ <- tagQuery(html) tagQ$ find("a")$ before(span())$ after(tags$table())$ allTags() #>
#>

#> #> #>
#>

#>
``` -------------------------------- ### POST /htmlTemplate Source: https://rstudio.github.io/htmltools/reference/htmlTemplate.html Processes an HTML template and returns a tagList object. If the template is a complete document, it is marked as an html_document. ```APIDOC ## htmlTemplate ### Description Process an HTML template and return a tagList object. If the template is a complete HTML document, then the returned object will also have class html_document. ### Parameters #### Arguments - **filename** (string) - Optional - Path to an HTML template file. Incompatible with text_. - **...** (any) - Optional - Variable values to use when processing the template. - **text_** (string) - Optional - A string to use as the template, instead of a file. Incompatible with filename. - **document_** (boolean/string) - Optional - Is this template a complete HTML document (TRUE), or a fragment (FALSE)? Defaults to "auto" which searches for "". ``` -------------------------------- ### Print HTML tags and objects Source: https://rstudio.github.io/htmltools/reference/print.html.html Use these S3 methods to control the output of HTML objects. Set the browse argument to TRUE to view in a browser or FALSE to output raw markup to the console. ```R # S3 method for class 'shiny.tag' print(x, browse = is.browsable(x), ...) # S3 method for class 'html' print(x, ..., browse = is.browsable(x)) ``` -------------------------------- ### takeSingletons Source: https://rstudio.github.io/htmltools/reference/singleton_tools.html Extracts and filters singleton objects from a tag hierarchy to prevent duplicates. ```APIDOC ## takeSingletons(ui, singletons = character(0), desingleton = TRUE) ### Description Returns a list containing the processed tag objects with duplicate singleton objects removed and the updated list of known singleton signatures. ### Parameters #### Arguments - **ui** (Tag object or list) - Required - Tag object or lists of tag objects. - **singletons** (character) - Optional - Character vector of singleton signatures already encountered. - **desingleton** (logical) - Optional - Whether encountered singletons should have the singleton attribute removed. ### Response - **ui** (list) - The processed tag objects with duplicate singleton objects removed. - **singletons** (list) - The list of known singleton signatures. ``` -------------------------------- ### tagList Function Source: https://rstudio.github.io/htmltools/reference/tagList.html Creates a list of tags with methods for printing and converting to character strings. ```APIDOC ## tagList() ### Description Create a `list()` of tags with methods for `print()`, `as.character()`, etc. ### Method `tagList(...) ### Arguments `...` A collection of tags. ### Examples ```R tagList( h1("Title"), h2("Header text", style = "color: red;"), p("Text here") ) #>

Title

#>

Header text

#>

Text here

``` ``` -------------------------------- ### Render Tags into HTML Source: https://rstudio.github.io/htmltools/reference/renderTags.html Use `renderTags` to convert tag objects into HTML, handling head content, singletons, and dependencies. It's generally intended for library use rather than direct user calls. ```R renderTags(x, singletons = character(0), indent = 0) ``` -------------------------------- ### css() Function Source: https://rstudio.github.io/htmltools/reference/css.html Generates a CSS style declaration string from named arguments, automatically converting R-friendly argument names to CSS property names. ```APIDOC ## css(..., collapse_ = "") ### Description Convenience function for building CSS style declarations (i.e. the string that goes into a style attribute, or the parts that go inside curly braces in a full stylesheet). ### Parameters #### Arguments - **...** (named arguments) - Required - Named style properties, where the name is the property name and the argument is the property value. - **collapse_** (character) - Optional - Character to use to collapse properties into a single string; defaults to "". ### Details - CSS uses '-' as a separator; use '.' or '_' in R function arguments (e.g., font.size becomes font-size). - To mark a property as !important, add '!' to the end of the property name (requires quoting the name). - Values are converted to strings using paste(collapse = " "). - Properties with NULL or empty string values are dropped. ### Request Example css(font.family = "Helvetica, sans-serif", margin = "10px", "padding!" = "6px") ### Response - **Return Value** (string) - A formatted CSS declaration string. ``` -------------------------------- ### Conditional Attributes and Children in Tags Source: https://rstudio.github.io/htmltools/articles/htmltools.html Demonstrates how to conditionally render HTML attributes and children by setting them to NULL or using conditional R expressions. ```R tags$div(class = "header", id = NULL, NULL, "line 2" ) ##
line 2
tags$div(class = "header", id = if (FALSE) 100, if (FALSE) "line 1", "line 2" ) ##
line 2
``` -------------------------------- ### Print Generic Lists of Tags Source: https://rstudio.github.io/htmltools/news/index.html Printing a generic list() of tag-like objects using as.tags() no longer results in an error. This fix improves the handling of list structures containing tags. ```R print(as.tags(x)) ``` -------------------------------- ### Save HTML object to file Source: https://rstudio.github.io/htmltools/reference/save_html.html Use this function to write HTML content to a file path or connection. The default method handles dependency copying and allows customization of background color and language attributes. ```R save_html(html, file, ...) ``` ```R save_html(html, file, background = "white", libdir = "lib", lang = "en", ...) ``` -------------------------------- ### Print Method for HTML/Tags Source: https://rstudio.github.io/htmltools/reference/print.html.html S3 method for printing HTML that prints markup or renders HTML in a web browser. ```APIDOC ## S3 method for class 'shiny.tag' print(x, browse = is.browsable(x), ...) ### Description S3 method for printing HTML that prints markup or renders HTML in a web browser. ### Method S3 Method ### Parameters #### Arguments - **x** (any) - The value to print. - **browse** (logical) - If TRUE, the HTML will be rendered and displayed in a browser (or possibly another HTML viewer supplied by the environment via the `viewer` option). If FALSE then the HTML object's markup will be rendered at the console. - **...** (any) - Additional arguments passed to print. ## S3 method for class 'html' print(x, ..., browse = is.browsable(x)) ### Description S3 method for printing HTML that prints markup or renders HTML in a web browser. ### Method S3 Method ### Parameters #### Arguments - **x** (any) - The value to print. - **browse** (logical) - If TRUE, the HTML will be rendered and displayed in a browser (or possibly another HTML viewer supplied by the environment via the `viewer` option). If FALSE then the HTML object's markup will be rendered at the console. - **...** (any) - Additional arguments passed to print. ``` -------------------------------- ### Embedding Raw HTML Safely with HTML() Source: https://rstudio.github.io/htmltools/articles/htmltools.html Illustrates how to safely embed raw HTML content into a Shiny UI using the HTML() function. Avoid passing user input directly to HTML() to prevent security vulnerabilities like XSS. ```R tags$div( "Raw HTML!" ) ##
<strong>Raw HTML!</strong>
``` ```R tags$div( HTML("Raw HTML!") ) ##
Raw HTML!
``` ```R tags$div( HTML(input$text) ) ``` -------------------------------- ### HTML Dependencies Source: https://rstudio.github.io/htmltools/reference/index.html Functions for defining, attaching, and resolving HTML dependencies like CSS and JavaScript files. ```APIDOC ## HTML Dependencies ### Description Manage external assets required by HTML components. ### Methods htmlDependency, htmlDependencies, attachDependencies, findDependencies, subtractDependencies, suppressDependencies ``` -------------------------------- ### Find Parent Tags with tagQuery Source: https://rstudio.github.io/htmltools/articles/tagQuery.html Use $parent() to select the direct parent of selected tags, or $parents() to select all ancestors. These methods traverse up the tag tree. ```R (html <- div(div(a(class = "foo")), span(a()))) #> ``` ```R tagQ <- tagQuery(html) tagQ$find("a.foo")$parent()$selectedTags() #> ``` ```R tagQ$find("a.foo")$parents()$selectedTags() #> ``` -------------------------------- ### browsable and is.browsable functions Source: https://rstudio.github.io/htmltools/reference/browsable.html Functions to control the default rendering behavior of HTML objects in the R console. ```APIDOC ## browsable(x, value = TRUE) ### Description By default, HTML objects display their HTML markup at the console when printed. `browsable` can be used to make specific objects render as HTML by default when printed at the console. ### Parameters - **x** (object) - Required - The object to make browsable or not. - **value** (boolean) - Optional - Whether the object should be considered browsable. ### Value `browsable` returns `x` with an extra attribute to indicate that the value is browsable. ## is.browsable(x) ### Description Checks if an object is currently marked as browsable. ### Parameters - **x** (object) - Required - The object to check. ### Value Returns `TRUE` if the value is browsable, or `FALSE` if not. ``` -------------------------------- ### Passing Lists of Children to Tags Source: https://rstudio.github.io/htmltools/articles/htmltools.html Shows how to pass a list of R objects as children to a tag function, which will render each element as a child of the tag. ```R tags$div(class="header", checked=NA, list( tags$p("Ready to take the Shiny tutorial? If so"), tags$a(href="shiny.posit.co/tutorial", "Click Here!"), "Thank you" ) ) ##
##

Ready to take the Shiny tutorial? If so

## Click Here! ## Thank you ##
``` -------------------------------- ### bindFillRole Source: https://rstudio.github.io/htmltools/reference/bindFillRole.html Configures an HTML tag to act as a fill container or a fill item, allowing it to grow and shrink based on its parent's dimensions. ```APIDOC ## bindFillRole ### Description Create fill containers and items. If a fill item is a direct child of a fill container, and that container has an opinionated height, then the item is allowed to grow and shrink to its container's size. ### Parameters - **x** (tag object) - Required - A tag() object. Can also be a valid tagQuery() input if .cssSelector is specified. - **...** (unused) - Optional - Currently unused. - **item** (boolean) - Optional - Whether or not to treat x as a fill item. - **container** (boolean) - Optional - Whether or not to treat x as a fill container. Note, this will set the CSS display property on the tag to flex. - **overwrite** (boolean) - Optional - Whether or not to override previous calls to bindFillRole(). - **.cssSelector** (character) - Optional - A character string containing a CSS selector for targeting particular (inner) tag(s) of interest. ### Value The original tag object (x) with additional attributes (and a htmlDependency()). ``` -------------------------------- ### Add Class to Tag using tagQuery Source: https://rstudio.github.io/htmltools/reference/tagQuery.html Demonstrates how to use tagQuery to find a specific tag (e.g., 'a') within a structure and add a class to it. Requires the htmltools package. ```R tagQ <- tagQuery(div(a())) tagQ$find("a")$addClass("foo") #> `$allTags()`: #>
#> #>
#> #> `$selectedTags()`: #> [[1]] #> #> tagQ #> `$allTags()`: #>
#> #>
#> #> `$selectedTags()`: `$allTags()` ``` -------------------------------- ### Define HTML tag structure Source: https://rstudio.github.io/htmltools/reference/builder.html Constructs a nested HTML document structure using the tags list. ```R tags$html( tags$head( tags$title('My first page') ), tags$body( h1('My first heading'), p('My first paragraph, with some ', strong('bold'), ' text.'), div( id = 'myDiv', class = 'simpleDiv', 'Here is a div with some attributes.' ) ) ) ```