I am trying to dynamically create and loop through htmlwidgets such as DT, plotly, or rbokeh to generate an automated kni
I'll copy my response to the Github issue below.
Good question, and I think others will be helped by this discussion. It might be easiest to start by building something like what you propose from scratch without the aid of rmarkdown.
# https://github.com/ramnathv/htmlwidgets/pull/110#issuecomment-216562703
library(plotly)
library(htmltools)
library(markdown)
library(shiny)
browsable(
attachDependencies(
tagList(
tags$div(
class="tabs",
tags$ul(
class="nav nav-tabs",
role="tablist",
tags$li(
tags$a(
"data-toggle"="tab",
href="#tab-1",
"Iris"
)
),
tags$li(
tags$a(
"data-toggle"="tab",
href="#tab-2",
"Cars"
)
)
),
tags$div(
class="tab-content",
tags$div(
class="tab-pane active",
id="tab-1",
as.widget(
plot_ly(
iris,
x = iris[["Sepal.Length"]],
y = iris[["Sepal.Width"]],
mode = "markers"
)
)
),
tags$div(
class="tab-pane",
id="tab-2",
as.widget(
plot_ly(
cars,
x = speed,
y = dist,
mode = "markers"
)
)
)
)
)
),
# attach dependencies
# see https://github.com/rstudio/rmarkdown/blob/master/R/html_document.R#L235
list(
rmarkdown::html_dependency_jquery(),
shiny::bootstrapLib()
)
)
)
There is probably a better way to make this work, but until someone sets me straight, we can take the approach from above and use it in rmarkdown. Unfortunately, this is still very manual. For more reference, here is the code that RStudio uses to build tabsets.
---
title: "tabs and htmlwidgets"
author: "Kent Russell"
date: "May 3, 2016"
output: html_document
---
```{r echo=FALSE, message=FALSE, warning=FALSE}
library(plotly)
library(htmltools)
library(magrittr)
# make a named list of plots for demonstration
# the names will be the titles for the tabs
plots <- list(
"iris" = plot_ly(
iris,
x = iris[["Sepal.Length"]],
y = iris[["Sepal.Width"]],
mode = "markers"
),
"cars" = plot_ly(
cars,
x = speed,
y = dist,
mode = "markers"
)
)
# create our top-level div for our tabs
tags$div(
# create the tabs with titles as a ul with li/a
tags$ul(
class="nav nav-tabs",
role="tablist",
lapply(
names(plots),
function(p){
tags$li(
tags$a(
"data-toggle"="tab",
href=paste0("#tab-",p),
p
)
)
}
)
),
# fill the tabs with our plotly plots
tags$div(
class="tab-content",
lapply(
names(plots),
function(p){
tags$div(
# make the first tabpane active
class=ifelse(p==names(plots)[1],"tab-pane active","tab-pane"),
# id will need to match the id provided to the a href above
id=paste0("tab-",p),
as.widget(plots[[p]])
)
}
)
)
) %>%
# attach the necessary dependencies
# since we are manually doing what rmarkdown magically does for us
attachDependencies(
list(
rmarkdown::html_dependency_jquery(),
shiny::bootstrapLib()
)
)
```