Title: | Tools for HTML |
---|---|
Description: | Tools for HTML generation and output. |
Authors: | Joe Cheng [aut], Carson Sievert [aut, cre] , Barret Schloerke [aut] , Winston Chang [aut] , Yihui Xie [aut], Jeff Allen [aut], Posit Software, PBC [cph, fnd] |
Maintainer: | Carson Sievert <[email protected]> |
License: | GPL (>= 2) |
Version: | 0.5.8.9000 |
Built: | 2024-11-05 05:28:30 UTC |
Source: | https://github.com/rstudio/htmltools |
An S3 method for converting arbitrary values to a value that can be used as
the child of a tag or tagList
. The default implementation simply calls
as.character()
.
as.tags(x, ...)
as.tags(x, ...)
x |
Object to be converted. |
... |
Any additional parameters. |
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.
bindFillRole( x, ..., item = FALSE, container = FALSE, overwrite = FALSE, .cssSelector = NULL )
bindFillRole( x, ..., item = FALSE, container = FALSE, overwrite = FALSE, .cssSelector = NULL )
x |
a |
... |
currently unused. |
item |
whether or not to treat |
container |
whether or not to treat |
overwrite |
whether or not to override previous calls to
|
.cssSelector |
A character string containing a CSS selector for
targeting particular (inner) tag(s) of interest. For more details on what
selector(s) are supported, see |
The original tag object (x
) with additional attributes (and a
htmlDependency()
).
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)
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)
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.
browsable(x, value = TRUE) is.browsable(x)
browsable(x, value = TRUE) is.browsable(x)
x |
The object to make browsable or not. |
value |
Whether the object should be considered browsable. |
You can override the default browsability of an HTML object by explicitly
passing browse = TRUE
(or FALSE
) to the print
function.
browsable
returns x
with an extra attribute to indicate
that the value is browsable.
is.browsable
returns TRUE
if the value is browsable, or
FALSE
if not.
Create an R object that represents an HTML tag. For convenience, common HTML
tags (e.g., <div>
) can be created by calling for their tag name directly
(e.g., div()
). To create less common HTML5 (or SVG) tags (e.g.,
<article>
), use the tags
list collection (e.g., tags$article()
). To
create other non HTML/SVG tags, use the lower-level tag()
constructor.
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)
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)
... |
Tag attributes (named arguments) and children (unnamed arguments).
A named argument with an
|
.noWS |
Character vector used to omit some of the whitespace that would
normally be written around this tag. Valid options include |
.renderHook |
A function (or list of functions) to call when the |
_tag_name |
A character string to use for the tag name. |
varArgs |
List of tag attributes and children. |
A list()
with a shiny.tag
class that can be converted into an
HTML string via as.character()
and saved to a file with save_html()
.
tagList()
, withTags()
, tagAppendAttributes()
, tagQuery()
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.' ) ) ) # html5 <audio> with boolean control attribute # https://www.w3.org/TR/html5/infrastructure.html#sec-boolean-attributes tags$audio( controls = NA, tags$source( src = "myfile.wav", type = "audio/wav" ) ) # suppress the whitespace between tags tags$span( tags$strong("I'm strong", .noWS="outside") )
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.' ) ) ) # html5 <audio> with boolean control attribute # https://www.w3.org/TR/html5/infrastructure.html#sec-boolean-attributes tags$audio( controls = NA, tags$source( src = "myfile.wav", type = "audio/wav" ) ) # suppress the whitespace between tags tags$span( tags$strong("I'm strong", .noWS="outside") )
Easily generates a .png file (or other graphics file) from a plotting expression.
capturePlot( expr, filename = tempfile(fileext = ".png"), device = defaultPngDevice(), width = 400, height = 400, res = 72, ... )
capturePlot( expr, filename = tempfile(fileext = ".png"), device = defaultPngDevice(), width = 400, height = 400, res = 72, ... )
expr |
A plotting expression that generates a plot (or yields an object
that generates a plot when printed, like a ggplot2). We evaluate this
expression after activating the graphics device ( |
filename |
The output filename. By default, a temp file with |
device |
A graphics device function; by default, this will be either
|
width , height , res , ...
|
Additional arguments to the |
plotTag()
saves plots as a self-contained <img>
tag.
# Default settings res <- capturePlot(plot(cars)) # View result if (interactive()) browseURL(res) # Clean up unlink(res) # Custom width/height pngpath <- tempfile(fileext = ".png") capturePlot(plot(pressure), pngpath, width = 800, height = 375) if (interactive()) 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 ) if (interactive()) browseURL(svgpath) unlink(svgpath) }
# Default settings res <- capturePlot(plot(cars)) # View result if (interactive()) browseURL(res) # Clean up unlink(res) # Custom width/height pngpath <- tempfile(fileext = ".png") capturePlot(plot(pressure), pngpath, width = 800, height = 375) if (interactive()) 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 ) if (interactive()) browseURL(svgpath) unlink(svgpath) }
Copies an HTML dependency to a subdirectory of the given directory. The
subdirectory name will be name-version (for example,
"outputDir/jquery-1.11.0"). You may set options(htmltools.dir.version = FALSE)
to suppress the version number in the subdirectory name.
copyDependencyToDir(dependency, outputDir, mustWork = TRUE)
copyDependencyToDir(dependency, outputDir, mustWork = TRUE)
dependency |
A single HTML dependency object. |
outputDir |
The directory in which a subdirectory should be created for this dependency. |
mustWork |
If |
In order for disk-based dependencies to work with static HTML files, it's generally necessary to copy them to either the directory of the referencing HTML file, or to a subdirectory of that directory. This function makes it easier to perform that copy.
The dependency with its src
value updated to the new
location's absolute path.
makeDependencyRelative()
can be used with the returned
value to make the path relative to a specific directory.
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).
css(..., collapse_ = "")
css(..., collapse_ = "")
... |
Named style properties, where the name is the property name and the argument is the property value. See Details for conversion rules. |
collapse_ |
(Note that the parameter name has a trailing underscore
character.) Character to use to collapse properties into a single string;
likely |
CSS uses '-'
(minus) as a separator character in property names, but
this is an inconvenient character to use in an R function argument name.
Instead, you can use '.'
(period) and/or '_'
(underscore) as
separator characters. For example, css(font.size = "12px")
yields
"font-size:12px;"
.
To mark a property as !important
, add a '!'
character to the end
of the property name. (Since '!'
is not normally a character that can be
used in an identifier in R, you'll need to put the name in double quotes or
backticks.)
Argument values will be converted to strings using
paste(collapse = " ")
. Any property with a value of NULL
or
""
(after paste) will be dropped.
padding <- 6 css( font.family = "Helvetica, sans-serif", margin = paste0(c(10, 20, 10, 20), "px"), "padding!" = if (!is.null(padding)) padding )
padding <- 6 css( font.family = "Helvetica, sans-serif", margin = paste0(c(10, 20, 10, 20), "px"), "padding!" = if (!is.null(padding)) padding )
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.
defaultPngDevice()
defaultPngDevice()
A graphics device function.
Walks a hierarchy of tags looking for attached dependencies.
findDependencies(tags, tagify = TRUE)
findDependencies(tags, tagify = TRUE)
tags |
A tag-like object to search for dependencies. |
tagify |
Whether to tagify the input before searching for dependencies. |
A list of htmlDependency()
objects.
Marks the given text as HTML, which means the tag functions will know not to perform HTML escaping on it.
HTML(text, ..., .noWS = NULL)
HTML(text, ..., .noWS = NULL)
text |
The text value to mark with HTML |
... |
Any additional values to be converted to character and concatenated together |
.noWS |
Character vector used to omit some of the whitespace that would
normally be written around this HTML. Valid options include |
The input text
, but marked as HTML.
el <- div(HTML("I like <u>turtles</u>")) cat(as.character(el))
el <- div(HTML("I like <u>turtles</u>")) cat(as.character(el))
Convenience method that provides an implementation of the
base::print()
method for HTML content.
html_print( html, background = "white", viewer = getOption("viewer", utils::browseURL) )
html_print( html, background = "white", viewer = getOption("viewer", utils::browseURL) )
html |
HTML content to print |
background |
Background color for web page |
viewer |
A function to be called with the URL or path to the generated
HTML page. Can be |
Invisibly returns the URL or path of the generated HTML page.
Gets or sets the HTML dependencies associated with an object (such as a tag).
htmlDependencies(x) htmlDependencies(x) <- value attachDependencies(x, value, append = FALSE)
htmlDependencies(x) htmlDependencies(x) <- value attachDependencies(x, value, append = FALSE)
x |
An object which has (or should have) HTML dependencies. |
value |
An HTML dependency, or a list of HTML dependencies. |
append |
If FALSE (the default), replace any existing dependencies. If TRUE, add the new dependencies to the existing ones. |
attachDependencies
provides an alternate syntax for setting
dependencies. It is similar to local({htmlDependencies(x) <- value;
x})
, except that if there are any existing dependencies,
attachDependencies
will add to them, instead of replacing them.
As of htmltools 0.3.4, HTML dependencies can be attached without using
attachDependencies
. Instead, they can be added inline, like a child
object of a tag or tagList()
.
# 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" ) # A few different ways to add the dependency to tag objects: # Inline as a child of the div() div("Code here", dep) # Inline in a tagList tagList(div("Code here"), dep) # With attachDependencies attachDependencies(div("Code here"), dep)
# 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" ) # A few different ways to add the dependency to tag objects: # Inline as a child of the div() div("Code here", dep) # Inline in a tagList tagList(div("Code here"), dep) # With attachDependencies attachDependencies(div("Code here"), dep)
Define an HTML dependency (i.e. CSS and/or JavaScript bundled in a directory). HTML dependencies make it possible to use libraries like jQuery, Bootstrap, and d3 in a more composable and portable way than simply using script, link, and style tags.
htmlDependency( name, version, src, meta = NULL, script = NULL, stylesheet = NULL, head = NULL, attachment = NULL, package = NULL, all_files = TRUE )
htmlDependency( name, version, src, meta = NULL, script = NULL, stylesheet = NULL, head = NULL, attachment = NULL, package = NULL, all_files = TRUE )
name |
Library name |
version |
Library version |
src |
Unnamed single-element character vector indicating the full path of the library directory. Alternatively, a named character string with one or more elements, indicating different places to find the library; see Details. |
meta |
Named list of meta tags to insert into document head |
script |
Script(s) to include within the document head (should be
specified relative to the |
stylesheet |
Stylesheet(s) to include within the document (should be
specified relative to the |
head |
Arbitrary lines of HTML to insert into the document head |
attachment |
Attachment(s) to include within the document head. See Details. |
package |
An R package name to indicate where to find the |
all_files |
Whether all files under the |
Each dependency can be located on the filesystem, at a relative or
absolute URL, or both. The location types are indicated using the names of
the src
character vector: file
for filesystem directory,
href
for URL. For example, a dependency that was both on disk and at
a URL might use src = c(file=filepath, href=url)
.
script
can be given as one of the following:
a character vector specifying various scripts to include relative to the
value of src
.
Each is expanded into its own <script>
tag
A named list with any of the following fields:
src
,
integrity
, &
crossorigin
,
any other valid <script>
attributes.
allowing the use of SRI to ensure the integrity of packages downloaded from
remote servers.
Eg: script = list(src = "min.js", integrity = "hash")
An unnamed list, containing a combination of named list with the fields mentioned previously, and strings. Eg:
script = list(list(src = "min.js"), "util.js", list(src = "log.js"))
script = "pkg.js"
is equivalent to
script = list(src = "pkg.js")
.
attachment
can be used to make the indicated files available to the
JavaScript on the page via URL. For each element of attachment
, an
element <link id="DEPNAME-ATTACHINDEX-attachment" rel="attachment" href="...">
is inserted, where DEPNAME
is name
. The value of
ATTACHINDEX
depends on whether attachment
is named or not; if
so, then it's the name of the element, and if not, it's the 1-based index
of the element. JavaScript can retrieve the URL using something like
document.getElementById(depname + "-" + index + "-attachment").href
.
Note that depending on the rendering context, the runtime value of the href
may be an absolute, relative, or data URI.
htmlDependency
should not be called from the top-level of a package
namespace with absolute paths (or with paths generated by
system.file()
) and have the result stored in a variable. This is
because, when a binary package is built, R will run htmlDependency
and store the path from the building machine's in the package. This path is
likely to differ from the correct path on a machine that downloads and
installs the binary package. If there are any absolute paths, instead of
calling htmlDependency
at build-time, it should be called at
run-time. This can be done by wrapping the htmlDependency
call in a
function.
An object that can be included in a list of dependencies passed to
attachDependencies()
.
Use attachDependencies()
to associate a list of
dependencies with the HTML it belongs with.
The shape of the htmlDependency
object is described (in TypeScript code)
here.
Escape HTML entities contained in a character vector so that it can be safely included as text or an attribute value within an HTML document
htmlEscape(text, attribute = FALSE)
htmlEscape(text, attribute = FALSE)
text |
Text to escape |
attribute |
Escape for use as an attribute value |
Character vector with escaped text.
Use "magic" HTML comments to protect regions of HTML from being modified by text processing tools.
htmlPreserve(x) extractPreserveChunks(strval) restorePreserveChunks(strval, chunks)
htmlPreserve(x) extractPreserveChunks(strval) restorePreserveChunks(strval, chunks)
x |
A character vector of HTML to be preserved. |
strval |
Input string from which to extract/restore chunks. |
chunks |
The |
Text processing tools like markdown and pandoc are designed to turn
human-friendly markup into common output formats like HTML. This works well
for most prose, but components that generate their own HTML may break if
their markup is interpreted as the input language. The htmlPreserve
function is used to mark regions of an input document as containing pure HTML
that must not be modified. This is achieved by substituting each such region
with a benign but unique string before processing, and undoing those
substitutions after processing.
htmlPreserve
returns a single-element character vector with
"magic" HTML comments surrounding the original text (unless the original
text was empty, in which case an empty string is returned).
extractPreserveChunks
returns a list with two named elements:
value
is the string with the regions replaced, and chunks
is
a named character vector where the names are the IDs and the values are the
regions that were extracted.
restorePreserveChunks
returns a character vector with the
chunk IDs replaced with their original values.
# htmlPreserve will prevent "<script>alert(10*2*3);</script>" # from getting an <em> tag inserted in the middle markup <- paste(sep = "\n", "This is *emphasized* text in markdown.", htmlPreserve("<script>alert(10*2*3);</script>"), "Here is some more *emphasized text*." ) extracted <- extractPreserveChunks(markup) markup <- extracted$value # Just think of this next line as Markdown processing output <- gsub("\\*(.*?)\\*", "<em>\\1</em>", markup) output <- restorePreserveChunks(output, extracted$chunks) output
# htmlPreserve will prevent "<script>alert(10*2*3);</script>" # from getting an <em> tag inserted in the middle markup <- paste(sep = "\n", "This is *emphasized* text in markdown.", htmlPreserve("<script>alert(10*2*3);</script>"), "Here is some more *emphasized text*." ) extracted <- extractPreserveChunks(markup) markup <- extracted$value # Just think of this next line as Markdown processing output <- gsub("\\*(.*?)\\*", "<em>\\1</em>", markup) output <- restorePreserveChunks(output, extracted$chunks) output
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
, and can be passed to the function
renderDocument()
to get the final HTML text.
htmlTemplate(filename = NULL, ..., text_ = NULL, document_ = "auto")
htmlTemplate(filename = NULL, ..., text_ = NULL, document_ = "auto")
filename |
Path to an HTML template file. Incompatible with
|
... |
Variable values to use when processing the template. |
text_ |
A string to use as the template, instead of a file. Incompatible
with |
document_ |
Is this template a complete HTML document ( |
Load HTML, text, or rendered Markdown from a file and turn into HTML.
includeHTML(path) includeText(path) includeMarkdown(path) includeCSS(path, ...) includeScript(path, ...)
includeHTML(path) includeText(path) includeMarkdown(path) includeCSS(path, ...) includeScript(path, ...)
path |
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. |
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.
includeText
escapes its contents, but does no other processing.
This means that hard breaks and multiple spaces will be rendered as they
usually are in HTML: as a single space character. If you are looking for
preformatted text, wrap the call with pre()
, or consider using
includeMarkdown
instead.
The includeMarkdown
function requires the markdown
package.
These S3 methods are necessary to allow HTML tags to print themselves in knitr/rmarkdown documents.
knit_print.shiny.tag(x, ..., inline = FALSE) knit_print.html(x, ..., inline = FALSE) knit_print.shiny.tag.list(x, ..., inline = FALSE) knit_print.html_dependency(x, ..., inline = FALSE)
knit_print.shiny.tag(x, ..., inline = FALSE) knit_print.html(x, ..., inline = FALSE) knit_print.shiny.tag.list(x, ..., inline = FALSE) knit_print.html_dependency(x, ..., inline = FALSE)
x |
Object to knit_print |
... |
Additional knit_print arguments |
inline |
Whether or not the code chunk is inline. |
Change a dependency's absolute path to be relative to one of its parent directories.
makeDependencyRelative(dependency, basepath, mustWork = TRUE)
makeDependencyRelative(dependency, basepath, mustWork = TRUE)
dependency |
A single HTML dependency with an absolute path. |
basepath |
The path to the directory that |
mustWork |
If |
The dependency with its src
value updated to the new
location's relative path.
If baspath
did not appear to be a parent directory of the dependency's
directory, an error is raised (regardless of the value of mustWork
).
Parses/normalizes CSS color strings, and returns them as strings in
"#RRGGBB"
and/or "#RRGGBBAA"
format. Understands hex colors in 3, 4, 6,
and 8 digit forms, rgb()
/rgba()
, hsl()
/hsla()
, and color keywords.
parseCssColors(str, mustWork = TRUE)
parseCssColors(str, mustWork = TRUE)
str |
CSS color strings |
mustWork |
If true, invalid color strings will cause an error; if false,
then the result will contain |
Note that parseCssColors
may return colors in #RRGGBBAA
format. Such
values are not understood by Internet Explorer, and must be converted to
rgba(red, green, blue, alpha)
format to be safe for the web.
A vector of strings in #RRGGBB
or #RRGGBBAA
format (the latter is
only used for colors whose alpha values are less than FF
), or NA
for
invalid colors when mustWork
is false. Such strings are suitable for
use in plots, or parsing with col2rgb()
(be sure to pass alpha = TRUE
to prevent the alpha channel from being discarded).
parseCssColors(c( "#0d6efd", "#DC35457F", "rgb(32,201,151)", " rgba( 23 , 162 , 184 , 0.5 ) ", "hsl(261, 51%, 51%)", "cornflowerblue" ))
parseCssColors(c( "#0d6efd", "#DC35457F", "rgb(32,201,151)", " rgba( 23 , 162 , 184 , 0.5 ) ", "hsl(261, 51%, 51%)", "cornflowerblue" ))
<img>
tagCapture a plot as a self-contained <img>
tag
plotTag( expr, alt, device = defaultPngDevice(), width = 400, height = 400, pixelratio = 2, mimeType = "image/png", deviceArgs = list(), attribs = list(), suppressSize = c("none", "x", "y", "xy") )
plotTag( expr, alt, device = defaultPngDevice(), width = 400, height = 400, pixelratio = 2, mimeType = "image/png", deviceArgs = list(), attribs = list(), suppressSize = c("none", "x", "y", "xy") )
expr |
A plotting expression that generates a plot (or yields an object that generates a plot when printed, like a ggplot2). |
alt |
A single-element character vector that contains a text description of the image. This is used by accessibility tools, such as screen readers for vision impaired users. |
device |
A graphics device function; by default, this will be either
|
width , height
|
The width/height that the generated tag should be displayed at, in logical (browser) pixels. |
pixelratio |
Indicates the ratio between physical and logical units of
length. For PNGs that may be displayed on high-DPI screens, use |
mimeType |
The MIME type associated with the |
deviceArgs |
A list of additional arguments that should be included when
the |
attribs |
A list of additional attributes that should be included on the
generated |
suppressSize |
By default, |
A browsable()
HTML <img>
tag object. Print it at
the console to preview, or call as.character()
on it to view the HTML
source.
capturePlot()
saves plots as an image file.
img <- plotTag({ plot(cars) }, "A plot of the 'cars' dataset", width = 375, height = 275) if (interactive()) img if (interactive() && capabilities("cairo")) { plotTag( plot(pressure), "A plot of the 'pressure' dataset", device = grDevices::svg, width = 375, height = 275, pixelratio = 1/72, mimeType = "image/svg+xml" ) }
img <- plotTag({ plot(cars) }, "A plot of the 'cars' dataset", width = 375, height = 275) if (interactive()) img if (interactive() && capabilities("cairo")) { plotTag( plot(pressure), "A plot of the 'pressure' dataset", device = grDevices::svg, width = 375, height = 275, pixelratio = 1/72, mimeType = "image/svg+xml" ) }
S3 method for printing HTML that prints markup or renders HTML in a web browser.
## S3 method for class 'shiny.tag' print(x, browse = is.browsable(x), ...) ## S3 method for class 'html' print(x, ..., browse = is.browsable(x))
## S3 method for class 'shiny.tag' print(x, browse = is.browsable(x), ...) ## S3 method for class 'html' print(x, ..., browse = is.browsable(x))
x |
The value to print. |
browse |
If |
... |
Additional arguments passed to print. |
Create the appropriate HTML markup for including dependencies in an HTML document.
renderDependencies( dependencies, srcType = c("href", "file"), encodeFunc = urlEncodePath, hrefFilter = identity )
renderDependencies( dependencies, srcType = c("href", "file"), encodeFunc = urlEncodePath, hrefFilter = identity )
dependencies |
A list of |
srcType |
The type of src paths to use; valid values are |
encodeFunc |
The function to use to encode the path part of a URL. The default should generally be used. |
hrefFilter |
A function used to transform the final, encoded URLs of script and stylesheet files. The default should generally be used. |
An HTML()
object suitable for inclusion in the head of an
HTML document.
This function renders html_document
objects, and returns a string with
the final HTML content. It calls the renderTags()
function to
convert any shiny.tag objects to HTML. It also finds any any web dependencies
(created by htmlDependency()
) that are attached to the tags, and
inserts those. To do the insertion, this function finds the string
"<!-- HEAD_CONTENT -->"
in the document, and replaces it with the web
dependencies.
renderDocument(x, deps = NULL, processDep = identity)
renderDocument(x, deps = NULL, processDep = identity)
x |
An object of class |
deps |
Any extra web dependencies to add to the html document. This can
be an object created by |
processDep |
A function that takes a "raw" html_dependency object and
does further processing on it. For example, when |
An HTML()
string, with UTF-8 encoding.
Renders tags (and objects that can be converted into tags using
as.tags()
) into HTML. (Generally intended to be called from web
framework libraries, not directly by most users–see
print.html()
for higher level rendering.)
renderTags(x, singletons = character(0), indent = 0) doRenderTags(x, indent = 0)
renderTags(x, singletons = character(0), indent = 0) doRenderTags(x, indent = 0)
x |
Tag object(s) to render |
singletons |
A list of singleton signatures to consider already rendered; any matching singletons will be dropped instead of rendered. (This is useful (only?) for incremental rendering.) |
indent |
Initial indent level, or |
doRenderTags
is intended for very low-level use; it ignores
render hooks, singletons, head, and dependency handling, and simply renders the given tag
objects as HTML. Please use renderTags()
if x
has not already handled its dependencies
and render hooks.
renderTags
returns a list with the following variables:
head
: An HTML()
string that should be included in <head>
.
singletons
: Character vector of singleton signatures that are
known after rendering.
dependencies
: A list of resolved htmlDependency()
objects.
html
: An HTML()
string that represents the main HTML that was rendered.
doRenderTags
returns a simple HTML()
string.
Given a list of dependencies, removes any redundant dependencies (based on name equality). If multiple versions of a dependency are found, the copy with the latest version number is used.
resolveDependencies(dependencies, resolvePackageDir = TRUE)
resolveDependencies(dependencies, resolvePackageDir = TRUE)
dependencies |
A list of |
resolvePackageDir |
Whether to resolve the relative path to an absolute
path via |
dependencies A list of htmlDependency()
objects with
redundancies removed.
An S3 generic method for saving an HTML-like object to a file. The default
method copies dependency files to the directory specified via libdir
.
save_html(html, file, ...) ## Default S3 method: save_html(html, file, background = "white", libdir = "lib", lang = "en", ...)
save_html(html, file, ...) ## Default S3 method: save_html(html, file, background = "white", libdir = "lib", lang = "en", ...)
html |
HTML content to print. |
file |
File path or connection. If a file path containing a sub-directory, the sub-directory must already exist. |
... |
Further arguments passed to other methods. |
background |
Background color for web page. |
libdir |
Directory to copy dependencies to. |
lang |
Value of the |
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.
singleton(x, value = TRUE) is.singleton(x)
singleton(x, value = TRUE) is.singleton(x)
x |
|
value |
Whether the object should be a singleton. |
Functions for manipulating singleton()
objects in tag
hierarchies. Intended for framework authors.
surroundSingletons(ui) takeSingletons(ui, singletons = character(0), desingleton = TRUE)
surroundSingletons(ui) takeSingletons(ui, singletons = character(0), desingleton = TRUE)
ui |
Tag object or lists of tag objects. See builder topic. |
singletons |
Character vector of singleton signatures that have already
been encountered (i.e. returned from previous calls to
|
desingleton |
Logical value indicating whether singletons that are encountered should have the singleton attribute removed. |
surroundSingletons
preprocesses a tag object by changing any
singleton X into <!--SHINY.SINGLETON[sig]-->X'<!--/SHINY.SINGLETON[sig]-->
where sig is the sha1 of X, and X' is X minus the singleton attribute.
takeSingletons
returns a list with the elements ui
(the
processed tag objects with any duplicate singleton objects removed) and
singletons
(the list of known singleton signatures).
Remove a set of dependencies from another list of dependencies. The set of dependencies to remove can be expressed as either a character vector or a list; if the latter, a warning can be emitted if the version of the dependency being removed is later than the version of the dependency object that is causing the removal.
subtractDependencies(dependencies, remove, warnOnConflict = TRUE)
subtractDependencies(dependencies, remove, warnOnConflict = TRUE)
dependencies |
A list of |
remove |
A list of |
warnOnConflict |
If |
A list of htmlDependency()
objects that don't intersect
with remove
.
This suppresses one or more web dependencies. It is meant to be used when a dependency (like a JavaScript or CSS file) is declared in raw HTML, in an HTML template.
suppressDependencies(...)
suppressDependencies(...)
... |
Names of the dependencies to suppress. For example,
|
htmlTemplate()
for more information about using HTML
templates.
Adds a hook to call on a tag()
object when it is is rendered as HTML (with,
for example, print()
, renderTags()
, as.tags()
, etc).
tagAddRenderHook(tag, func, replace = FALSE)
tagAddRenderHook(tag, func, replace = FALSE)
tag |
A |
func |
A function (hook) to call when the |
replace |
If |
The primary motivation for tagAddRenderHook()
is to create tags that can
change their attributes (e.g., change CSS classes) depending upon the context
in which they're rendered (e.g., use one set of CSS classes in one a page
layout, but a different set in another page layout). In this situation,
tagAddRenderHook()
is preferable to tagFunction()
since the latter is more a
"black box" in the sense that you don't know anything about the tag structure
until it's rendered.
A tag()
object with a .renderHooks
field containing a list of functions
(e.g. func
). When the return value is rendered (such as with as.tags()
),
these functions will be called just prior to writing the HTML.
# Have a place holder div and return a span instead obj <- div("example", .renderHook = function(x) { x$name <- "span" x }) obj$name # "div" print(obj) # Prints as a `span` # Add a class to the tag # Should print a `span` with class `"extra"` spanExtra <- tagAddRenderHook(obj, function(x) { tagAppendAttributes(x, class = "extra") }) spanExtra # Replace the previous render method # Should print a `div` with class `"extra"` divExtra <- tagAddRenderHook(obj, replace = TRUE, function(x) { tagAppendAttributes(x, class = "extra") }) divExtra # Add more child tags spanExtended <- tagAddRenderHook(obj, function(x) { tagAppendChildren(x, " ", tags$strong("bold text")) }) spanExtended # 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 # Ignore the original tag and return something completely new. newObj <- tagAddRenderHook(obj, function(x) { tags$p("Something else") }) newObj
# Have a place holder div and return a span instead obj <- div("example", .renderHook = function(x) { x$name <- "span" x }) obj$name # "div" print(obj) # Prints as a `span` # Add a class to the tag # Should print a `span` with class `"extra"` spanExtra <- tagAddRenderHook(obj, function(x) { tagAppendAttributes(x, class = "extra") }) spanExtra # Replace the previous render method # Should print a `div` with class `"extra"` divExtra <- tagAddRenderHook(obj, replace = TRUE, function(x) { tagAppendAttributes(x, class = "extra") }) divExtra # Add more child tags spanExtended <- tagAddRenderHook(obj, function(x) { tagAppendChildren(x, " ", tags$strong("bold text")) }) spanExtended # 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 # Ignore the original tag and return something completely new. newObj <- tagAddRenderHook(obj, function(x) { tags$p("Something else") }) newObj
Append (tagAppendAttributes()
), check existence (tagHasAttribute()
),
and obtain the value (tagGetAttribute()
) of HTML attribute(s).
tagAppendAttributes(tag, ..., .cssSelector = NULL) tagHasAttribute(tag, attr) tagGetAttribute(tag, attr)
tagAppendAttributes(tag, ..., .cssSelector = NULL) tagHasAttribute(tag, attr) tagGetAttribute(tag, attr)
tag |
a tag object. |
... |
Attributes to append as named argument-value pairs. A named
argument with an |
.cssSelector |
A character string containing a CSS selector
for targeting particular (inner) tags of interest. At the moment, only a
combination of
type (e.g,
|
attr |
The name of an attribute. |
tagAppendChildren()
, tagQuery()
html <- div(a()) tagAppendAttributes(html, class = "foo") tagAppendAttributes(html, .cssSelector = "a", class = "bar") tagAppendAttributes(html, contenteditable = NA) tagHasAttribute(div(foo = "bar"), "foo") tagGetAttribute(div(foo = "bar"), "foo")
html <- div(a()) tagAppendAttributes(html, class = "foo") tagAppendAttributes(html, .cssSelector = "a", class = "bar") tagAppendAttributes(html, contenteditable = NA) tagHasAttribute(div(foo = "bar"), "foo") tagGetAttribute(div(foo = "bar"), "foo")
Modify the contents (aka children) of a tag object.
tagAppendChild(tag, child, .cssSelector = NULL) tagAppendChildren(tag, ..., .cssSelector = NULL, list = NULL) tagSetChildren(tag, ..., .cssSelector = NULL, list = NULL) tagInsertChildren(tag, after, ..., .cssSelector = NULL, list = NULL)
tagAppendChild(tag, child, .cssSelector = NULL) tagAppendChildren(tag, ..., .cssSelector = NULL, list = NULL) tagSetChildren(tag, ..., .cssSelector = NULL, list = NULL) tagInsertChildren(tag, after, ..., .cssSelector = NULL, list = NULL)
tag |
a tag object. |
child |
A child element to append to a parent tag. |
.cssSelector |
A character string containing a CSS selector
for targeting particular (inner) tags of interest. At the moment, only a
combination of
type (e.g,
|
... |
a collection of |
list |
Deprecated. Use |
after |
an integer value (i.e., subscript) referring to the child position to append after. |
tagAppendAttributes()
, tagQuery()
html <- div(a(), h1()) tagAppendChild(html, span()) tagAppendChild(html, .cssSelector = "a", span()) tagAppendChildren(html, span(), p()) tagAppendChildren(html, .cssSelector = "a", span(), p()) tagSetChildren(html, span(), p()) tagInsertChildren(html, after = 1, span(), p())
html <- div(a(), h1()) tagAppendChild(html, span()) tagAppendChild(html, .cssSelector = "a", span()) tagAppendChildren(html, span(), p()) tagAppendChildren(html, .cssSelector = "a", span(), p()) tagSetChildren(html, span(), p()) tagInsertChildren(html, after = 1, span(), p())
Create 'lazily' rendered HTML tags (and/or htmlDependencies()
).
tagFunction(func)
tagFunction(func)
func |
a function with no arguments that returns HTML tags and/or dependencies. |
When possible, use tagAddRenderHook()
to provide both a tag
structure and utilize a render function.
myDivDep <- tagFunction(function() { if (isTRUE(getOption("useDep", TRUE))) { htmlDependency( name = "lazy-dependency", version = "1.0", src = "" ) } }) myDiv <- attachDependencies(div(), myDivDep) renderTags(myDiv) withr::with_options(list(useDep = FALSE), renderTags(myDiv))
myDivDep <- tagFunction(function() { if (isTRUE(getOption("useDep", TRUE))) { htmlDependency( name = "lazy-dependency", version = "1.0", src = "" ) } }) myDiv <- attachDependencies(div(), myDivDep) renderTags(myDiv) withr::with_options(list(useDep = FALSE), renderTags(myDiv))
Create a list()
of tags with methods for print()
, as.character()
,
etc.
tagList(...)
tagList(...)
... |
A collection of tags. |
tagList( h1("Title"), h2("Header text", style = "color: red;"), p("Text here") )
tagList( h1("Title"), h2("Header text", style = "color: red;"), p("Text here") )
tagQuery()
provides a
jQuery
inspired interface for querying and modifying
tag()
(and tagList()
) objects.
tagQuery(tags)
tagQuery(tags)
tags |
A class with methods that are described below. This class can't be
used directly inside other tag()
or a renderTags()
context, but
underlying HTML tags may be extracted via $allTags()
or
$selectedTags()
.
For performance reasons, the input tag structure to tagQuery()
will be
altered into a consistently expected shape.
Some alterations include:
tags flattening their $children
fields into a single list()
tags relocating any attribute html_dependency() to be located in
$children'
tagList()
-like structures relocating any attribute html dependency to
be a entry in its list structure.
While the resulting tag shape has possibly changed,
tagQuery()
's' resulting tags will still render
to the same HTML value (ex: renderTags()
) and
HTML dependencies (ex: findDependencies()
).
To get started with using tagQuery()
, visit
https://rstudio.github.io/htmltools/articles/tagQuery.html.
Unless otherwise stated, tagQuery()
methods accept a character
vector as input.
Query methods identify particular subsets of the root tag using CSS selectors (or R functions).
$find(cssSelector)
: Get the descendants of
each selected tag, filtered by a cssSelector
.
$children(cssSelector = NULL)
: Get the direct
children of each selected tag, optionally filtered by a
cssSelector
.
siblings(cssSelector = NULL)
: Get the
siblings of each selected tag, optionally filtered by a
cssSelector
.
$parent(cssSelector = NULL)
: Get the parent
of each selected tag, optionally filtered by a cssSelector
.
$parents(cssSelector = NULL)
: Get the
ancestors of each selected tag, optionally filtered by a
cssSelector
.
$closest(cssSelector = NULL)
: For each selected tag, get the closest
ancestor tag (including itself) satisfying a cssSelector
. If
cssSelector = NULL
, it is equivalent to calling $selectedTags()
.
$filter(fn)
: Filter the selected tags to those for which fn(x, i)
returns TRUE
. In addition to an R function with two arguments
(the selected tag x
and the index i
), fn
may also be a valid
CSS selector.
$length()
: Number of tags that have been selected.
$resetSelected()
: Reset selected tags to the $allTags()
tag. Useful
in combination with $replaceWith()
since it empties the selection.
Unlike query methods, modify methods modify the tagQuery()
object.
$addClass(class)
: Adds class(es) to each selected tag.
$removeClass(class)
: Removes class(es) to each selected tag.
$toggleClass(class)
: Adds class(es) that don't already exist and
removes class(es) that do already exist (for each selected tag).
$hasClass(class)
: Does each selected tag have all the provided
class(es)?
$addAttrs(...)
: Add a set of attributes to each selected tag.
$removeAttrs(attrs)
: Remove a set of attributes from each
selected tag.
$hasAttrs(attr)
: Do each selected tags have all of the attributes?
$append(...)
: For each selected tag, insert ...
after any
existing children.
$prepend(...)
: For each selected tag, insert ...
before any
existing children.
$after(...)
: Add all ...
objects as siblings after each of the
selected tags.
$before(...)
: Add all ...
objects as siblings before each of
the selected tags.
$each(fn)
: Modify each selected tag with a function fn
. fn
should accept two arguments: the first is the selected tag and second
is the selected tags position index. Since the selected tag is a
reference, any modifications to it will also modify the tagQuery()
object.
$replaceWith(...)
: Replace all selected tags with ...
in the
root tag and clear the selection.
$remove(...)
: Remove all selected tags from the root tag and
clear the current selection.
$empty()
: Remove any children of each selected tag. Use this
method before calling $append(...)
to replace the children of
each selected tag, with other content.
$allTags()
: Return the (possibly modified) root tags
.
$selectedTags()
: Return a tagList()
of the currently selected
tags.
tagQ <- tagQuery(div(a())) tagQ$find("a")$addClass("foo") tagQ # To learn more, visit https://rstudio.github.io/htmltools/articles/tagQuery.html
tagQ <- tagQuery(div(a())) tagQ$find("a")$addClass("foo") tagQ # To learn more, visit https://rstudio.github.io/htmltools/articles/tagQuery.html
Encode characters in a URL path. This is the same as
utils::URLencode()
with reserved = TRUE
except that
/
is preserved.
urlEncodePath(x)
urlEncodePath(x)
x |
A character vector. |
Checks that the argument is valid for use as a CSS unit of length.
validateCssUnit(x)
validateCssUnit(x)
x |
The unit to validate. Will be treated as a number of pixels if a unit is not specified. |
NULL
and NA
are returned unchanged.
Single element numeric vectors are returned as a character vector with the
number plus a suffix of "px"
.
Single element character vectors must be "auto"
, "fit-content"
or "inherit"
, a number, or a length calculated by the "calc"
CSS function. If the number has a suffix, it must be valid: px
,
\%
, ch
, em
, rem
, pt
, in
, cm
,
mm
, ex
, pc
, vh
, vw
, vmin
, or
vmax
.
If the number has no suffix, the suffix "px"
is appended.
Any other value will cause an error to be thrown.
A properly formatted CSS unit of length, if possible. Otherwise, will throw an error.
validateCssUnit("10%") validateCssUnit(400) #treated as '400px'
validateCssUnit("10%") validateCssUnit(400) #treated as '400px'
tags
This function makes it simpler to write HTML-generating code. Instead of
needing to specify tags
each time a tag function is used, as in
tags$div()
and tags$p()
, code inside withTags
is
evaluated with tags
searched first, so you can simply use
div()
and p()
.
withTags(code, .noWS = NULL)
withTags(code, .noWS = NULL)
code |
A set of tags. |
.noWS |
Default whitespace behavior for all tags within this call to
|
If your code uses an object which happens to have the same name as an
HTML tag function, such as source()
or summary()
, it will call
the tag function. To call the intended (non-tags function), specify the
namespace, as in base::source()
or base::summary()
.
# Using tags$ each time tags$div(class = "myclass", tags$h3("header"), tags$p("text") ) # Equivalent to above, but using withTags withTags( div(class = "myclass", h3("header"), p("text") ) ) # Setting .noWS for all tags in withTags() withTags( div( class = "myclass", h3("header"), p("One", strong(span("two")), "three") ), .noWS = c("outside", "inside") )
# Using tags$ each time tags$div(class = "myclass", tags$h3("header"), tags$p("text") ) # Equivalent to above, but using withTags withTags( div(class = "myclass", h3("header"), p("text") ) ) # Setting .noWS for all tags in withTags() withTags( div( class = "myclass", h3("header"), p("One", strong(span("two")), "three") ), .noWS = c("outside", "inside") )