rhtmlwidgetshtmltools

How to use htmltools::attachDependencies?


Here is an example of how I "manually" add a HTML dependency to a datatable. This works fine. When I try with attachDependencies, the dependency is not attached.

library(DT)
library(htmltools)

dep <- htmlDependency(
  name = "colResize", 
  version = "1.6.1", 
  src = normalizePath("colResize"),
  script = "jquery.dataTables.colResize.js",
  stylesheet = "jquery.dataTables.colResize.css",
  all_files = FALSE
)

dat <- iris

datatable(
  dat,
  options = list(
    colResize = list()
  )
) %>% attachDependencies(dep, append = TRUE)

Why does this code not work?


Solution

  • I don't think it has anything to do with the way you're using it. The function attachDependencies() adds the object as an attribute, not as a dependency:

    function (x, value, append = FALSE) 
    {
        value <- asDependencies(value)
        if (append) {
            old <- attr(x, "html_dependencies", TRUE)
            htmlDependencies(x) <- c(old, value)
        }
        else { htmlDependencies(x) <- value }
        return(x)
    }
    

    However, without this function, you could still add your dependency in one line instead of three. I know that's not what you're looking for, but it's an option.

    dtable$dependencies <- append(dtable$dependencies, list(dep))
    

    With my example:

    dep <- htmlDependency(
      name = "colResize", version = "1.6.1", 
      src = c(href = "https://cdn.jsdelivr.net/gh/dhobi/datatables.colResize/"),
      script = "jquery.dataTables.colResize.js",
      stylesheet = "jquery.dataTables.colResize.css",
      all_files = FALSE)
    
    dtable <- datatable(iris, options = list(colResize = list()))
    
    dtable$dependencies <- append(dtable$dependencies, list(dep))
    
    dtable
    

    enter image description here