Recommended way to initialize JS renderer in 'asis' R Markdown chunk

Viewed 592

'asis' chunks are very useful to output a list of objects in a Markdown document, see following examples : Highcharter, DT, Leaflet, ...

However, in the above examples, the list of object won't print if the renderer hasn't been called once in a previous chunk, so that it gets initialized : this is a tricky workaround, and I found the solution more by trial / error than by finding it in documentation.

This is a reproducible issue also posted on https://github.com/rstudio/rmarkdown/issues/1877 :

---
title: "Test"
output:
  html_document
---



```{r,echo=F}
library(DT)
library(rmarkdown)
library(purrr)
library(knitr)

df_list <- list("cars" = mtcars, "flowers" = iris)

knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
```

```{r}
# If this first initialization isn't run, tabs won't print
DT::datatable(data.frame())
```

# Test tabs {.tabset}

```{r, results='asis' }
imap(df_list, ~{
  cat('## Subtab ',.y,'\n')
  cat('\n')
  DT::datatable(.x) %>%
    htmltools::tagList() %>% as.character() %>% cat() })

```
 

  
3 Answers

If you really need 'asis', then you add extra dependencies manually such as JavaScript and CSS. You can do it with knitr::knit_meta_add().

```{r, results='asis'}
library(purrr)
data.frame() %>%
  DT::datatable() %>%
  knitr::knit_print() %>%
  attr('knit_meta') %>%
  knitr::knit_meta_add() %>%
  invisible()

df_list <- list("cars" = mtcars, "flowers" = iris)
imap(df_list, ~{
      cat('## Subtab ',.y,'\n')
      cat('\n')
      cat(knitr::knit_print(DT::datatable(.x)))})
```

You can output multiple datatables without asis. Just put the list of widgets into tagList()

```{r}
library(purrr)
list("cars" = mtcars, "flowers" = iris) %>%
  map(~DT::datatable(.x)) %>%
  htmltools::tagList()
```

The answer to my question has been given by @cderv :
https://github.com/rstudio/rmarkdown/issues/1877#issuecomment-679864674

The results = 'asis' is now more documented in https://bookdown.org/yihui/rmarkdown-cookbook/results-asis.html#results-asis . It is aimed at generating raw mardown content from a R chunk. Anything must result in a text output, and implicitly that means no knitr magic really happens for any R object in those chunk, because knitr does no adjustment when knit_printing the content (as it is juts text)

I think I would not use result = 'asis' to cat() a complex R object like an htmlwidget. You found a workaround but you may encounter other issues.

As this answer has been liked by @yihui, it gives a hint that cat + asis on htmlwidget should be used at one's own risk.

However, I'll personnaly continue to use the workarounds mentioned in the question, because as long as it works I find it very practical.

Thanks @atusi & @cderv for their valuable input.

Related