A few weeks ago I gave a talk at BARUG (and wrote a post) about blogging with the excellent knitr-jekyll
repo. Yihui’s system is fantastic, but it does have one drawback: None of those fancy new htmlwidgets packages seem to work…
A few people have run into this. I recently figured out how to fix it for this blog (which required a bit of time reading through the rmarkdown source), so I thought I’d write it up in case it helps anyone else, or my future-self.
You can add a line to build.R
which calls a small wrapper function I cobbled together (brocks::htmlwidgts_deps
), add a snippet of liquid syntax to ./_layouts/post.html
, and you’re away.
Often, when you ‘knit’ an .Rmd file to html, (perhaps without knowing it) you’re doing it via the rmarkdown
package, which adds its own invisible magic to the process. Behind the scenes, rmarkdown
uses knitr
to convert the file to markdown format, and then uses pandoc
to convert the markdown to HTML.
While knitr
executes R code and embeds results, htmlwidgets packages (such as leaflet
, DiagrammR
, threejs
, and metricsgraphics
) also have js and css dependencies. These are handled by rmarkdown
‘s second step, and so don’t get included when using knitr
alone.
The rmarkdown
invisible magic works as follows:
- It parses the .Rmd for special dependencies objects, linking to the js/css source (by calling
knitr::knit_meta
) - It then (by default) combines their source-code into a huge
data:uri
blob, which it writes to a temp-file - This is injected into the the final HTML file, by passing it to
pandoc
‘s--include-in-header
argument
Happily, including bits of HTML in other bits of HTML is one of Jekyll’s strengths, and it’s possible to high-jack the internals of rmarkdown
to do something appropriate. I did this with a little function htmlwdigets_deps
, which:
-
Copies the js/css dependencies from the R packages, …read more
Source:: r-bloggers.com