2
votes

I need to generate multiple htmlwidgets within a loop in an RMarkdown document. This is accomplished using htmltools::tagList. The following snippet will generate HTML output with 2 level 2 headings and a datatable in each section. The only problem is that I specified toc: true but though tags$h2(headers[i]) will render a level 2 headings on the page, those headings are not picked up by the table of contents. Is there a way get these headings in the TOC?

---
output: 
  html_document:
    toc: true
---

## level 2 heading 0 - this one in TOC

```{r}
library(DT)
library(htmltools)

headers <- c("level 2 heading 1", "level 2 heading 2")
html_tags <- vector(mode = "list", length = 2*length(headers))
for (i in 1:length(headers)) {
  html_tags[[(2*i)-1]] <- tags$h2(headers[i])
  html_tags[[(2*i)]] <- list(list(datatable(iris)))
}

tagList(html_tags)
```

Note that in the result below the heading generated using "##" shows up in the table of contents, but the headings from the tagList call, though they render correctly in the document, are now in the table of contents.

enter image description here

1
I cannot understand what you mean. Can you explain more? maybe you can check this page's code: stackoverflow.com/questions/43446523/…Peter Chen
See edits above. Headings render correctly, but only show in table of contents if input outside of the tagList using "##" in markdown syntaxMatt Pollock

1 Answers

2
votes

Try this:

---
output: 
  html_document:
    toc: true
---
```{r, echo=FALSE, message=FALSE, warning=FALSE}
library(DT)
library(htmltools)
```
```{r ,include = FALSE}
DT::datatable(iris)
```
## level 2 heading 0 - this one in TOC

```{r echo=FALSE, message=FALSE, warning=FALSE, results = 'asis'}
for (i in 1:2){
  cat("  \n## level 2 heading", i, "  \n")
   print(htmltools::tagList(DT::datatable(iris)))
  cat("  \n")
}
```

And the result is:
enter image description here

Maybe this is what you actually want.

Remember: You should avoid headers <- c("level 2 heading 1", "level 2 heading 2").
If you need hundred or thousand of headers, this isn't efficient and must waste too much time.